C++实现栈的操作(push和pop)
程序员文章站
2024-02-14 17:32:16
...
栈的组织形式:
如上图所示:栈也是有多个数据节点组成的,每个节点包含有数据域和指向下一个节点的指针域。并且每次的push、pop和判空都是操作的栈顶指针top。
栈中每个数据节点的定义:
class data_node{
public:
data_node() :data(0), next(NULL){}//default constructer function
data_node(int value) :data(value), next(NULL){}//include arg constructer function
int data;
data_node *next;//pointer that point to next node
};
栈的类的定义:
class my_stack{
public:
my_stack() :top(NULL){}
void push(data_node new_data);
void pop(data_node *pop_node);
bool empty();
data_node *top;
};
栈的push操作:
void my_stack::push(data_node new_data)
{
data_node *pnode = NULL;
pnode = new data_node(new_data.data);
pnode->next = top;
top = pnode;
}
void my_stack::pop(data_node *pop_node)
{
if (empty())
{
printf("this stack is empty\n");
return;
}
pop_node->data = top->data;
data_node *pnode = top;
top = top->next;
delete pnode;
}
bool my_stack::empty()
{
return (top == NULL);
}
完整的代码如下:
#include "stdafx.h"
#include <iostream>
#pragma warning(disable:4996)
#include <string>
using namespace std;
class data_node{
public:
data_node() :data(0), next(NULL){}//default constructer function
data_node(int value) :data(value), next(NULL){}//include arg constructer function
int data;
data_node *next;//pointer that point to next node
};
class my_stack{
public:
my_stack() :top(NULL){}
void push(data_node new_data);
void pop(data_node *pop_node);
bool empty();
data_node *top;
};
void my_stack::push(data_node new_data)
{
data_node *pnode = NULL;
pnode = new data_node(new_data.data);
pnode->next = top;
top = pnode;
}
void my_stack::pop(data_node *pop_node)
{
if (empty())
{
printf("this stack is empty\n");
return;
}
pop_node->data = top->data;
data_node *pnode = top;
top = top->next;
delete pnode;
}
bool my_stack::empty()
{
return (top == NULL);
}
int main()
{
data_node pop_node(0);
my_stack stack;
stack.push(3);
stack.push(2);
stack.push(6);//3,2,6
stack.pop(&pop_node);
//printf("is empty? %d\n", stack.empty());
printf("%2d ", pop_node.data);
stack.pop(&pop_node);
//printf("is empty? %d\n", stack.empty());
printf("%2d ", pop_node.data);
stack.pop(&pop_node);
printf("%2d\n ", pop_node.data);
printf("is empty? %d\n", stack.empty());
return 0;
}
上一篇: 一次C端线上缓存问题的总结
推荐阅读
-
C++实现栈的操作(push和pop)
-
java数组以及单向链表实现栈的push,pop
-
数据结构:实验四栈和队列的基本操作实现及其应用
-
C++ STL栈stack的底层实现和用法
-
java用两个栈实现队列的push和pop
-
C++实现用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
-
个人学习笔记:c++数组实现的模板队列和栈
-
算法————双栈实现队列、双队列实现栈、实现一个栈Push(出栈)Pop(入栈)Min(返回最小值的操作)的时间复杂度为O(1)
-
操作系统——页面置换算法c++的实现(fifo和lru)
-
无向图的邻接矩阵和邻接表实现各种操作 -- C++语言描述