1.栈的概念
展示只允许在其一端进行插入语删除操作的表。从定义上来说,栈其实也是线性表,因此栈也具备大多数线性表所具备的基本操作。但是,从定义上可知,栈在进行插入、删除操作时,只能在一端进行操作,这一端成为栈顶(top)。
栈最核心的操作主要是:进栈(Push)、出栈(Pop)、返回栈顶元素(Top)。 此外,栈还判断栈是否为空、创见栈、清空栈等操作。
既然是线性表,那么栈从实现方式来说主要有两种:顺序存储实现(数组)、链式存储实现(链表)。下面是链式存储实现方式下,站的数据结构定义:
- typedefstructNode*PtrToNode;
- typedefPtrToNodeStack;
- typedefstructNode
- {
- intElement;
- PtrToNodeNext;
- };
站的基本操作如下:
- //判断栈是否为空
- intIsEmpty(StackS);
- //创见栈
- StackCreateStack();
- //销毁栈
- voidDisposeStack(StackS);
- //清空栈
- voidMakeEmpty(StackS);
- //进栈
- voidPush(intX,StackS);
- //返回栈顶元素
- intTop(StackS);
- //出栈
- voidPop(StackS);
下面是一个完整的关于栈的基本操作的例子:
- #include<stdio.h>
- #include<stdlib.h>
- typedefstructNode*PtrToNode;
- typedefPtrToNodeStack;
- typedefstructNode
- {
- intElement;
- PtrToNodeNext;
- };
- intIsEmpty(StackS);
- StackCreateStack();
- voidDisposeStack(StackS);
- voidMakeEmpty(StackS);
- voidPush(intX,StackS);
- intTop(StackS);
- voidPop(StackS);
- //判断栈是否为空
- intIsEmpty(StackS)
- {
- returnS->Next==NULL;
- }
- //创建链栈
- StackCreateStack()
- {
- StackS=malloc(sizeof(structNode));
- if(S==NULL)
- {
- printf("Noenoughmemory!");
- returnNULL;
- }
- S->Next=NULL;
- MakeEmpty(S);
- returnS;
- }
- voidMakeEmpty(StackS)
- {
- if(S==NULL)
- {
- printf("UseCreateStackFirst!");
- }
- else
- {
- while(!IsEmpty(S))
- {
- Pop(S);
- }
- }
- }
- voidPush(intX,StackS)
- {
- PtrToNodeTmp;
- Tmp=malloc(sizeof(structNode));
- if(Tmp!=NULL)
- {
- Tmp->Element=X;
- Tmp->Next=S->Next;
- S->Next=Tmp;
- }
- else
- {
- printf("Outofspace!");
- }
- }
- voidPop(StackS)
- {
- if(IsEmpty(S))
- {
- printf("TheStackisEmpty!");
- }
- else
- {
- PtrToNodeTmp=S->Next;
- S->Next=Tmp->Next;
- free(Tmp);
- }
- }
- intTop(StackS)
- {
- if(IsEmpty(S))
- {
- printf("Thestackisempty!");
- return0;
- }
- else
- {
- returnS->Next->Element;
- }
- }
- intmain(void)
- {
- StackS=CreateStack();
- inti;
- for(i=0;i<5;i++)
- {
- Push(i,S);
- }
- while(!IsEmpty(S))
- {
- printf("%d\n",Top(S));
- Pop(S);
- }
- return0;
- }