#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int status;
typedef int ElemType;
#define MAXSIZE 100
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
status InitStack(SqStack *s)
{
s->base=(ElemType *)malloc(sizeof(ElemType)*MAXSIZE);
if(!s->base)
exit(OVERFLOW);
s->top=s->base;
s->stacksize=MAXSIZE;
return OK;
}
status Push(SqStack *s,ElemType e)
{
if(s->top-s->base==s->stacksize)
return ERROR;
*(s->top)=e;
s->top++;
return OK;
}
status Pop(SqStack *s,ElemType *e)
{
if(s->top==s->base)
return ERROR;
s->top--;
*e=*(s->top);
return OK;
}
ElemType GetTop(SqStack s)
{
if(s.top!=s.base)
return *(s.top-1);
}
//链栈
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
status InitStackNode(LinkStack *s)
{
*s=NULL;
return OK;
}
status PushNode(LinkStack *s,ElemType e)
{
//LinkStack r=*s;不能用r代替??
StackNode *p=(StackNode *)malloc(sizeof(StackNode));
p->data=e;
p->next=*s;
*s=p;
return OK;
}
status PopNode(LinkStack *s,ElemType *e)
{
//LinkStack r=*s;
if(*s==NULL)
return ERROR;
*e=(*s)->data;
StackNode *temp=*s;
*s=(*s)->next;
free(temp);
return OK;
}
ElemType GetTopNode(LinkStack s)
{
if(s==NULL)
return ERROR;
return s->data;
}
int main()
{
//顺序栈
/*
SqStack s;
InitStack(&s);
Push(&s,1);
Push(&s,2);
Push(&s,3);
Push(&s,4);
printf("top of the stack: %d\n",GetTop(s));
ElemType a;
int num=4,i;
for(i=0;i<num;i++)
{
Pop(&s,&a);
printf("%d\n",a);
}*/
//链栈
LinkStack s;
InitStack(&s);
int i,num=5;
for(i=0;i<num;i++)
{
PushNode(&s,i+1);
printf("Push:%d\n",GetTopNode(s));
}
ElemType a;
for(i=0;i<num;i++)
{
PopNode(&s,&a);
printf("Pop:%d\n",a);
}
return 0;
}
数据结构C语言-顺序栈和链栈
最新推荐文章于 2021-04-10 23:13:24 发布