栈的定义
- 栈是限定仅在表尾进行插入和删除操作的线性表
- 把允许插入和删除的一端称为栈顶(top)另一端称为栈底(bottom)
- 不含任何元素的栈称为空栈,
- 是先进先出的线性表(LIFO结构)
- 栈的插入(push)操作,叫做进栈,也叫压栈,入栈。
- 栈的删除(pop)操作,叫做出栈,也叫弹栈。
栈的顺序存储结构
#include<stdio.h>
#define SIZE 10
typedef struct Node{
int data[SIZE];
int top;
}NODE,*PNODE;
bool push(PNODE,int);
bool pop(PNODE,int *);
void traverse(PNODE);
void init(PNODE);
int main(){
int val;
NODE S;
init(&S);
push(&S,1);//压栈
push(&S,2);
push(&S,3);
push(&S,4);
push(&S,5);
traverse(&S);//遍历
//出栈
if(pop(&S,&val)){
printf("出栈成功!出栈的元素是:%d\n",val);
}
else{
printf("出栈失败!\n");
}
traverse(&S);
return 0;
}
void init(PNODE pS){
pS->top=-1;
}
bool push(PNODE pS,int e){
if(pS->top==SIZE-1)
return false;
pS->top++;
pS->data[pS->top]=e;
return true;
}
bool pop(PNODE pS,int *pVal){
if(pS->top==-1)
return false;
*pVal=pS->data[pS->top];
pS->top--;
return true;
}
void traverse(PNODE pS){
int i=pS->top;
while(i>=0){
printf("%d ",pS->data[i]);
i--;
}
printf("\n");
}
栈的链式存储结构
具体讲解
https://blog.csdn.net/weixin_45461859/article/details/103724181
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *pNext;
}NODE,*PNODE;
typedef struct Stack{
PNODE pTop;
PNODE pBottom;
}STACK,*PSTACK;
void init(PSTACK);
void push(PSTACK,int);
void traverse(PSTACK);
bool pop(PSTACK,int *);
bool empty(PSTACK pS);
void clear(PSTACK);
int main(void){
int val;
STACK S;//STACK等价属于 struct Stack
init(&S);//初始化
push(&S,1);//压栈
push(&S,2);
push(&S,3);
push(&S,4);
push(&S,5);
traverse(&S);//遍历
//出栈
if(pop(&S,&val)){
printf("出栈成功!出栈的元素是:%d\n",val);
}
else{
printf("出栈失败!\n");
}
traverse(&S);
clear(&S);
traverse(&S);
return 0;
}
void init(PSTACK pS){
pS->pTop=(PNODE)malloc(sizeof(NODE));
if(NULL==pS->pTop){
printf("动态内存分配失败!\n");
exit(-1);
}
else{
pS->pBottom=pS->pTop;
pS->pTop->pNext=NULL;//pS->pBottom->pNext=NULL;
}
return;
}
void push(PSTACK pS,int val){
PNODE pNew=(PNODE)malloc(sizeof(NODE));
pNew->data=val;
pNew->pNext=pS->pTop;
pS->pTop=pNew;
return;
}
void traverse(PSTACK pS){
PNODE p=pS->pTop;
while(p!=pS->pBottom){
printf("%d ",p->data);
p=p->pNext;
}
printf("\n");
return;
}
bool empty(PSTACK pS){
if(pS->pTop==pS->pBottom)
return true;
return false;
}
//把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中
//出栈失败返回false 成功则返回true
bool pop(PSTACK pS,int * pVal){
if(empty(pS)){
return false;
}
else{
PNODE p=pS->pTop;
*pVal=p->data;
pS->pTop=pS->pTop->pNext;
free(p);
}
}
void clear(PSTACK pS){
if(empty(pS))
return;
else{
PNODE p=pS->pTop;
PNODE q=NULL;
while(p!=pS->pBottom){
q=p->pNext;
free(p);
p=q;
}
pS->pTop=pS->pBottom;
printf("栈已清空!\n");
}
}