参考书:《数据结构(C语言版|第2版)》严蔚敏 李冬梅 吴伟民 编著
栈是限定仅在表尾进行插入或者删除的线性表。
- 顺序栈
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
using namespace std;
typedef int SElemType;
#define MAXSIZE 100
typedef struct
{
SElemType *base; //栈底指针
SElemType *top; //栈顶指针
int stacksize; //栈可用的最大容量
} SqStack;
//初始化
int InitStack(SqStack &S)
{
S.base=new SElemType[MAXSIZE];
if(!S.base)
{
printf("存储分配失败");
exit(0);
}
else
{
S.top=S.base;
S.stacksize=MAXSIZE;
return 0;
}
}
//入栈
int Push(SqStack &S,SElemType e)
{
if(S.top-S.base==S.stacksize)
{
printf("栈满,入栈失败");
exit(0);
}
*S.top++=e;
return 0;
}
//出栈
SElemType Pop(SqStack &S)
{
if(S.top==S.base)
{
printf("栈空,出栈失败");
exit(0);
}
int e=*--S.top;
return e;
}
//取栈顶元素
SElemType GetTop(SqStack S)
{
if(S.top==S.base)
{
printf("栈空,取栈顶元素失败");
exit(0);
}
return *(S.top-1);
}
//求栈的元素个数
int length(SqStack S)
{
int len=S.top-S.base;
return len;
}
int main()
{
SqStack s;
InitStack(s);
Push(s,1);
Push(s,2);
Push(s,3);
int a=GetTop(s);
printf("Top=%d\n",a);
Pop(s);
int b=GetTop(s);
printf("Top=%d\n",b);
int len=length(s);
printf("length=%d\n",len);
}
- 链栈
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
using namespace std;
typedef int SElemType;
#define MAXSIZE 100
typedef struct StackNode
{
SElemType data;
struct StackNode *next;
} StackNode,*LinkStack;
//初始化
int InitStack(LinkStack &S)
{
S=NULL;
return 0;
}
//入栈
int Push(LinkStack &S,SElemType e)
{
LinkStack p;
p=new StackNode;
p->data=e;
p->next=S;
S=p;
return 0;
}
//出栈
SElemType Pop(LinkStack &S)
{
if(S==NULL)
{
printf("栈为空,出栈失败");
exit(0);
}
SElemType e=S->data;
LinkStack p;
p=S;
S=S->next;
delete p;
return e;
}
//取栈顶元素
SElemType GetTop(LinkStack S)
{
if(S!=NULL)
return S->data;
else cout<<"栈为空,取栈顶元素失败"<<endl;
return 0;
}
//遍历输出
void TraverseList(LinkStack S)
{
if(S==NULL)
return ;
else
{
cout<<S->data<<endl;
TraverseList(S->next);
}
}
int main()
{
LinkStack s;
InitStack(s);
Push(s,1);
Push(s,2);
int a=GetTop(s);
printf("a=%d\n",a);
TraverseList(s);
Pop(s);
int b=GetTop(s);
printf("a=%d\n",b);
Pop(s);
return 0;
}