//参考:http://blog.sina.com.cn/s/blog_8c5b746601019wxc.html
http://blog.csdn.net/zdcsky123/article/details/6668908
栈的顺序结构实现:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define STACKSIZE 100
typedef struct{
int data[STACKSIZE];
int top;
}SeqStack,*PSeqStack;
PSeqStack Init_SeqStack()
{
PSeqStack S;
S=(PSeqStack)malloc(sizeof(SeqStack));
if(S!=NULL)
S->top=-1;
return S;
}
int Empty_SeqStack(PSeqStack S)
{
if(S->top==-1)
return 1;
else
return 0;
}
int Push_SeqStack(PSeqStack S,int x)
{
if(S->top==STACKSIZE-1)
return 0;
else
{
S->top++;
S->data[S->top]=x;
return 1;
}
}
int Pop_SeqStack(PSeqStack S,int *x)
{
if(Empty_SeqStack(S)==1)
return 0;
else
{
*x=S->data[S->top];
S->top--;
return 1;
}
}
int GetTop_SeqStack(PSeqStack S)
{
if(Empty_SeqStack(S)==1)
{
printf("Empty Stack!\n");
return -1;
}
else
return S->data[S->top];
}
int Destory_SeqStack(PSeqStack *S)
{
if(*S)
{
free(*S);
*S=NULL;
return 1;
}
return 0;
}
int main()
{
PSeqStack s;
int x=0;
s=Init_SeqStack();
Push_SeqStack(s,1);
Push_SeqStack(s,2);
Push_SeqStack(s,3);
Push_SeqStack(s,4);
printf("Top:%d ",GetTop_SeqStack(s));
Destory_SeqStack(&s);
return 0;
}
栈的链式结构实现:
注意:指针方向是从栈顶(队尾)指向栈底(队首)。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define STACKSIZE 100
typedef struct StackNode
{
int data;
struct StackNode *next;
}LinkStackNode,*PLinkStackNode;
typedef struct
{
PLinkStackNode top;
}LinkStack,*PLinkStack;
PLinkStack Init_LinkStack()
{
PLinkStack S;
S=(PLinkStack)malloc(sizeof(LinkStack));
if(S)
S->top=NULL;
return S;
}
int Empty_LinkStack(PLinkStack S)
{
if(S->top==NULL)
return 1;
else
return 0;
}
void Push_LinkStack(PLinkStack S,int x)
{
PLinkStackNode p;
p=(PLinkStackNode)malloc(sizeof(LinkStackNode));
if(p!=NULL)
{
p->data=x;
p->next=S->top;
S->top=p;
}
}
void Pop_LinkStack(PLinkStack S,int *x)
{
PLinkStack p;
if(Empty_LinkStack(S)==1)
return;
else
{
p=S->top;
*x=S->top->data;
S->top=S->top->next;
free(p);
}
}
int GetTop_LinkStack(PLinkStack S)
{
if(Empty_LinkStack(S)==1)
{
printf("Empty Stack!\n");
return -1;
}
else
return S->top->data;
}
void Destory_LinkStack(PLinkStack *S)
{
PLinkStackNode p,q;
if(*S)
{
p=(*S)->top;
while(p)
{
q=p;
p=p->next;
free(q);
}
free(*S);
}
*S=NULL;
}
int main()
{
PLinkStack S;
int x=0;
S=Init_LinkStack();
Push_LinkStack(S,1);
Push_LinkStack(S,2);
Push_LinkStack(S,3);
Push_LinkStack(S,6);
printf("Top:%d ",GetTop_LinkStack(S));
Destory_LinkStack(&S);
return 0;
}