C++实现,采用链表存储,因为顺序存储较为简单,不再重复叙述。
#include <iostream>
using namespace std;
struct node //栈的节点
{
int data;
struct node *next;
};
struct linkStack
{
struct node *top; //指向栈顶节点
int lengthStack; //栈长度
};
//创建一个空栈
void create(struct linkStack *S)
{
S->top = NULL;
S->lengthStack = 0;
}
//入栈数据num
void stackInsert(struct linkStack *S, int num)
{
struct node *p = new node;
p->data = num;
if(S->top == NULL) //当栈为空时
S->top = p;
else //当栈不为空时
{
p->next = S->top;
S->top = p;
}
S->lengthStack++;
}
//出栈并打印出栈的数据
void stackPop(struct linkStack *S)
{
struct node *temp;
if(S->top != NULL)
{
temp = S->top;
S->top = S->top->next;
cout<<temp->data<<endl;
delete(temp);
S->lengthStack--;
}
}
int main()
{
linkStack S;
create(&S);
/********入栈*************/
stackInsert(&S, 1);
stackInsert(&S, 2);
stackInsert(&S, 3);
stackInsert(&S, 4);
/********出栈*************/
stackPop(&S);
stackPop(&S);
stackPop(&S);
stackPop(&S);
return 0;
}