顺序栈
#include<iostream>
using namespace std;
#define maxsize 20
typedef struct zhan1{
int *base;
int *top;
int stacksize;
}zhan;
bool initstack(zhan &s)//初始化栈
{
s.base=new int[maxsize];
s.top=s.base;
s.stacksize=maxsize;
return true;
}
bool destorystack(zhan &s)//销毁栈
{
free(s.base);
s.stacksize=0;
return true;
}
bool clearstack(zhan &s)//清空栈
{
s.top=s.base;
return true;
}
bool stackempty(zhan &s)//判断栈是否为空
{
if(s.base=s.top)
return true;
else
return false;
}
int stacklength(zhan &s)//栈的长度
{
return s.top-s.base;
}
int gettop(zhan &s)//取栈订元素
{
return *(s.top-1);
}
bool push(zhan &s,int x)//将元素压入栈
{
if(s.top-s.base==s.stacksize)
return false;
else
{
*s.top++=x;
return true;
}
}
bool pop(zhan &s,int &x)//将栈顶元素取出
{
if(s.top==s.base)
return false;
else
{
x=*--s.top;
return true;
}
}
int main()
{
zhan s;
int i,x,y,z;
initstack(s);
for(i=0;i<5;i++)
{
scanf("%d",&x);
push(s,x);
}
printf("%d\n",gettop(s));
pop(s,z);
printf("%d\n",z);
printf("%d\n",gettop(s));
return 0;
}
input
1 2 3 4 5
output
5
5
4
链栈
#include <iostream>
using namespace std;
typedef struct stackz{
int data;
struct stackz *next;
}zhan,*zhan1;
bool initstack(zhan1 &s)//链栈的初始化
{
s=NULL;
return true;
}
void push(zhan1 &s,int x)//链栈的入栈
{
zhan1 p;
p=new zhan;
p->data=x;
p->next=s;
s=p;
}
void pop(zhan1 &s,int x)//链栈的出栈
{
zhan1 p;
x=s->data;
p=s;
s=s->next;
delete p;
}
int gettop(zhan1 s)//取栈顶元素
{
if(s!=NULL)
{
return s->data;
}
}
int main()
{
zhan1 s;
int x,i;
initstack(s);
for(i=0;i<5;i++)
{
scanf("%d",&x);
push(s,x);
}
printf("%d\n",gettop(s));
pop(s,x);
printf("%d\n",gettop(s));
return 0;
}
input
1 2 3 4 5
output
5
4