//栈作为一种数据结构,是一种只能在一端进行插入和删除操作的特殊线性表。
//它按照后进先出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶
//栈具有记忆作用,对栈的插入与删除操作中,不需要改变栈底指针。
#include <iostream>
using namespace std;
struct list//定义栈节点结构
{
int data;
list *next;
};
class Stack//定义一个栈操作类
{
list *ptr;//栈指针
public:
Stack() {ptr = NULL;}
void push(int x);//入栈成员函数
int pop();//出栈成员函数
};
void Stack::push(int x)
{
list *newnode = new list;//为指针分配一个栈节点结构空间
newnode -> data = x;
newnode -> next = ptr;//当前栈节点结构中的指针指向的是上一个栈节点结构
ptr = newnode;//然后更新栈指针指向当前结构,所以说最后栈结构中的指针是NULL
//区别于队列,队列是上一个结构中的指针指向当前的结构
//ptrb -> next = newnode;
//ptrb = newnode;
//参考这里http://blog.youkuaiyun.com/maodewen11/article/details/8135712
}
int Stack::pop()
{
list *top;//临时备份指针,为了删除空间,防止内存泄露
int value;
if (ptr -> next == NULL)
cout << "呵呵,因为到底了,这个指针没法指谁了 ";
value = ptr -> data;
top = ptr;
ptr = ptr -> next;
delete top;
return value;
}
void main()
{
Stack A;
int arr[] = {5,2,8,1,4,3,9,7,6};
cout << "入栈顺序: ";
for (int i = 0; i < 9; i++)
{
cout << arr[i] << " ";
A.push(arr[i]);
}
cout << endl << "出栈顺序: ";
for (i = 0; i < 9; i++)
cout << A.pop() << " ";
cout << endl;
}