栈是一种只允许在一端进行插入和删除的线性表,通常将表中允许进行插入、删除操作的一端称为栈顶 (Top),表的另一端被称为栈底 (Bottom),栈的插入操作被形象地称为进栈或入栈,栈的删除操作称为出栈或退栈,当栈中没有元素时称为空栈。
特点:后进先出(LIFO)
知识点:
栈空状态 s->top=-1;栈满状态 s->top=MAXSIZE-1
出栈,判断栈空;入栈和读栈顶元素,判断栈满
空栈时,栈顶指针top=-1
进栈:先开辟空间,然后元素入栈 st->top++; st->data[st->top]=x;
出栈:元素先出栈,然后改变栈顶指针 *x=st->data[st->top]; st->top--;
栈的顺序存储结构
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
typedef struct
{
int data[MAXSIZE];
int top;
} SeqStack;
SeqStack *s;
//初始化顺序栈
SeqStack *init_SeqStack();
SeqStack *init_SeqStack()
{
SeqStack *s=(SeqStack *)malloc(sizeof(SeqStack));
s->top=-1;
return s;
}
//判空栈
int empty_SeqStack(SeqStack *s)
{
if(s->top==-1) return 1;
else return 0;
}
//入栈
int push_SeqStack(SeqStack *s,int x);
int push_SeqStack(SeqStack *s,int x)
{
if(s->top==MAXSIZE-1) return 0; //栈满不能入栈
else{
s->top++;
s->data[s->top]=x;
return 1;
}
}
//出栈
int pop_SeqStack(SeqStack *s,int *num);
int pop_SeqStack(SeqStack *s,int *num)
{
if(empty_SeqStack(s)) return 0; //栈空不能出栈
else{
*num=s->data[s->top]; //栈顶元素存入*num
s->top--;
return 1;
}
}
//取栈顶元素
int top_SeqStack(SeqStack *s);
int top_SeqStack(SeqStack *s)
{
if(empty_SeqStack(s)) return 0; //栈空不能出栈
else return (s->data[s->top]);
}
//打印栈元素
void print_SeqStack(SeqStack *s);
void print_SeqStack(SeqStack *s)
{
while(s->top !=-1)
{
printf("栈元素:%d\n",s->data[s->top--]);
}
}
int main()
{
int x;
SeqStack st={{1,2,3,4},3};
push_SeqStack(&st,5);
pop_SeqStack(&st,&x);
printf("出栈元素:%d\n",x);
print_SeqStack(&st);
return 0;
}
栈的链式存储结构
#include<stdio.h>
#include<stdlib.h>
typedef struct Stacknode
{
int data;
struct Stacknode *next;
}Lstack;
//初始化链栈
Lstack *init_Lstack();
Lstack *init_Lstack()
{
Lstack *top=(Lstack *)malloc(sizeof(Lstack));
top->next=NULL;
return top;
}
//入栈
void push_Lstack(Lstack *top,int x);
void push_Lstack(Lstack *top,int x)
{
Lstack *p;
p=(Lstack *)malloc(sizeof(Lstack));
if(p==NULL) //申请一个节点
{
printf("error");
exit(0);
}
p->data=x;
p->next=top->next;
top->next=p;
}
//出栈
int pop_Lstack(Lstack *top);
int pop_Lstack(Lstack *top)
{
Lstack *p;
int x;
if(top->next==NULL)
{
printf("Lstack is NULL!");
return;
}
p=top->next;
top->next=p->next;
x=p->data;
free(p);
return x;
}
void print_Lstack(Lstack *top);
void print_Lstack(Lstack *top)
{
Lstack *p;
p=top->next;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}
int main()
{
int x;
Lstack *top;
top=init_Lstack();
push_Lstack(top,1);
push_Lstack(top,2);
push_Lstack(top,3);
push_Lstack(top,4);
x=pop_Lstack(top);
printf("===%d\n",x);
print_Lstack(top);
return 0;
}