初学栈,用链表创建栈的基本代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node *next;
} Node,*LinkList;
LinkList Createzhan()//创建栈
{
LinkList top;
top=NULL;
return top;
}
bool StackEmpty(LinkList s)//判断栈是否为空,1代表空
{
if(s==NULL)
return 1;
else
return 0;
}
LinkList push(LinkList s,int x)//栈中插入元素
{
LinkList q,top=s;
q=(LinkList)malloc(sizeof(Node));
if(!q) return 0;
q->data=x;
q->next=top;
top=q;
return top;
}
LinkList pop(LinkList s,int &e)//删除栈顶元素
{
if(StackEmpty(s))
{
printf("栈为空。");
return s;
}
else
{
e=s->data;
LinkList p=s;
s=s->next;
free(p);
}
return s;
}
void GetTop(LinkList s,int &e)//取得栈顶元素
{
if(StackEmpty(s))
printf("栈为空。");
else
e=s->data;
}
void TravealPut(LinkList s)//遍历输出栈中元素
{
if(StackEmpty(s))
printf("栈为空。");
else
{
while(s!=NULL)
{
cout<<s->data<<" ";
s=s->next;
}
cout<<endl;
}
}
int main()
{
LinkList top;
top=Createzhan();
printf("输入一个放入栈的数据:");
int x;
cin>>x;
top=push(top,x);
top=push(top,x);
TravealPut(top);
int e;
GetTop(top,e);
cout<<e<<endl;
e=0;
top=pop(top,e);
cout<<StackEmpty(top)<<endl;
return 0;
}