1.顺序栈
#include <stdio.h>
#define MAXSIZE 20
typedef int ElemType;
typedef struct {
ElemType data[MAXSIZE];
int top;
}sqstack;
//1.构造空栈
bool InitStack(sqstack &s){
s.top=-1;
return true;
}
//2.把S置为空栈
bool clearstack(sqstack &s)
{
s.top=-1;
return true;
}
bool stackempty(sqstack s)
{
if(s.top=-1)
return true;
else
return flase;
}
//返回S的元素个数,即栈的长度
int stacklength(sqstack s)
{
return s.top+1;
}
bool Gettop(SqStack s,ElemType &e)
{
if(s.top==-1)
return false;
else
return true;
}
//6.插入元素e为新的栈顶元素
bool push(sqstack &s,ElemType e)
{
if(s.top ==MAXSIZE -1)
{
return false;
}
s.top++;
s.data[s.top]=e;
return true;
}
bool pop(sqstack &s,ElemType &e)
{
if(s.top==-1)
return false;
e=s.data[s.top];
s.top--;
return true;
}
bool stackTraverse(sqstack s)
{
int i;
i=0;
while(i<=s.top)
{
printf("%d",s.data[i++]);
}
printf("\n");
return flase;
}
int main(){
int j;
sqstack s;
int e;
if(initstack(s)==true)
for(j=1;j<=10;j++)
push(s,j);
printf("栈中元素依次为:\n");
stackTraverse(s);
pop(s,e);
printf("弹出的栈顶元素 e=%d\n",e);
printf("栈空否:%的(1:空 0:否\n",stackEmpty(s));
GetTop(s,e);
printf("栈顶元素 e=%d 栈的长度为%d\n",e,stackLength(s));
clearStack(s);
printf("清栈后,栈空否:%d\n",stackEmpty(s));
return 0;
}
2.链栈
#include <stdio.h>
typedef char ElemType;
typedef struct SNode{
ElemType data;
struct SNode *next;
}SNode *LinkStack;
//不带头节点的链栈
void initstack(LinkStack &Ls)
{
Ls=NULL;
}
bool Destroystack(Linkstack &Ls){
SNode* pre=Ls;
SNode* p;
if(pre == NULL)
return false;
p=pre->next;
while(p!=Null)
{
free(pre);
pre=p;
p=p->next;
}
free(pre);
return true;
}
bool push(Linkstck &Ls,ElemType e)
{
SNode* p;
p=(SNode *)malloc(sizeof(SNode));
p->data=e;p->next=Ls;
Ls=p;
return true;
}
bool pop(LinkStack &Ls,ElemType &e)
{
SNode* p;
if(Ls==NULL)
return false;
else
{
p=Ls;
e=p->data;
Ls=p->next;
free(p);
return true;
}
}
bool Gettop(LinkStack Ls,ElemType &e)
{
if(Ls==NULL)
return false;
else
{
e=Ls->data
return true;
}
}
bool stackEmpty(LinkStack Ls)
{
if(Ls==NULL)
return true;
else
return false;
}
int main(){
Linkstack Ls;
ElemType e;
printf("初始化栈Ls\n");
initstack(Ls);
printf("栈%s\n",(stackEmptty(Ls)==true?"空":"不空"));
printf("a进栈\n");
push(Ls,'a');
printf("b进栈\n");
push(Ls,'b');
printf("c进栈\n");
push(Ls,'c');
printf("d进栈\n");
push(Ls,'d');
printf("栈%s\n",(stackEmptty(Ls)==true?"空":"不空"));
GetTop(Ls,e);
printf("栈顶元素:%c\n",e);
printf("出栈次序:");
while(!stackEmpty(Ls)==true?"空":"不空")
{
pop(Ls,e);
printf("%c",e);
}
printf("\n");
Destroystack(Ls);