1.栈
后进先出,只对栈顶进行操作。
1.1 栈的顺序存储
· 结构体定义
typedef int ElemType;
#define MAXNUM 100
typedef struct SeqStack
{
ElemType s[MAXNUM];
int top; /* 栈顶指针 */
}SeqStack, *PSeqStack;
· 创建(空栈)
PSeqStack createEmptyStack_seq()
{
PSeqStack pastack;
pastack=(PSeqStack)malloc(sizeof(SeqStack));
if(pastack==NULL)
printf("out of space!\n");
else
pastack->top=-1;
return pastack;
}
空栈时,top=-1
· 压栈
void push_seq(PSeqStack pastack,ElemType x)
{
if(pastack->top>=MAXNUM-1)
printf("overflow!\n");
else{
pastack->top=pastack->top+1;
pastack->s[pastack->top]=x;
}
}
· 删除栈顶元素
ElemType pop_seq(PSeqStack pastack)
{
ElemType temp;
if(isEmptyStack_seq(pastack))
printf("Underflow!\n");
else{
temp=pastack->s[pastack->top];
pastack->top=pastack->top-1;
}
return temp;
}
1.2 栈的链式存储
· 结构体
typedef int DataType;
typedef struct Node{
DataType info;
struct Node *link;
}Node;
typedef struct LinkStack{
struct Node *top;
}LinkStack,*PLinkStack;
· 创建空栈
PLinkStack createEmptyStack_link()
{
PLinkStack plstack;
plstack=(PLinkStack)malloc(sizeof(LinkStack));
if(plstack!=NULL)
plstack->top=NULL;
else
printf("Out of Space!\n");
return plstack;
}
· 是否为空栈
int isEmptyStack(PLinkStack plstack)
{
return (plstack->top==NULL);
}
· 压栈
void push_link(PLinkStack plstack,DataType x)
{
Node *p;
p=(Node*)malloc(sizeof(Node));
if(p==NULL){
printf("Out of Space!\n");
}
else{
p->info=x;
p->link=plstack->top;
plstack->top=p;
}
}
· 删除栈顶元素
DataType pop_link(PLinkStack plstack)
{
Node *p;
DataType elem;
if(isEmptyStack(plstack))
printf("is empty!\n");
else{
p=plstack->top;
elem=p->info;
plstack->top=plstack->top->link;
free(p);
}
return elem;
}