1.什么叫堆栈?
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210307193543338.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3p4cjkxNg==,size_16,color_FFFFFF,t_70#pic_center)
2.堆栈的数据类型描述
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210307193627439.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3p4cjkxNg==,size_16,color_FFFFFF,t_70#pic_center)
3.堆栈顺序存储的C语言实现
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 10
#define ERROR -1
#define ElementType int
typedef struct SNode *Stack;
struct SNode{
ElementType Data[MaxSize];
int Top;
};
Stack PtrS;
Stack MakeEmpty()
{
Stack PtrS;
PtrS = (Stack)malloc(sizeof(struct SNode));
PtrS->Top=-1;
return PtrS;
}
void Push(ElementType item,Stack PtrS)
{
if(PtrS->Top==MaxSize){
printf("栈已满\n");
return;
}
else{
PtrS->Data[++(PtrS->Top)]=item;
return;
}
}
ElementType Pop(Stack PtrS)
{
if(PtrS->Top==-1){
printf("栈为空\n");
return ERROR;
}
else{
return PtrS->Data[(PtrS->Top)--];
}
}
int main()
{
int i;
PtrS=MakeEmpty();
Push(23,PtrS);
Push(28,PtrS);
Push(78,PtrS);
for(i=0;i<=PtrS->Top;i++ ){
printf("%d ",PtrS->Data[i]);
}
printf("\n");
printf("出栈为:%d\n",Pop(PtrS));
for(i=0;i<=PtrS->Top;i++ ){
printf("%d ",PtrS->Data[i]);
}
printf("\n");
return 0;
}
4.堆栈链式存储的C语言实现
#include<stdio.h>
#include<stdlib.h>
#define ElementType int
typedef struct SNode *Stack;
struct SNode{
ElementType Data;
Stack Next;
};
Stack PtrS;
Stack MakeEmpty()
{
Stack PtrS;
PtrS = (Stack)malloc(sizeof(struct SNode));
PtrS->Next=NULL;
return PtrS;
}
int IsEmpty(Stack PtrS)
{
return (PtrS->Next==NULL);
}
void Push(ElementType item,Stack PtrS)
{
Stack TmpCell;
TmpCell = (Stack)malloc(sizeof(struct SNode));
TmpCell->Data=item;
TmpCell->Next=PtrS->Next;
PtrS->Next=TmpCell;
}
ElementType Pop(Stack PtrS)
{
ElementType TopElement;
Stack FirstCell;
if(IsEmpty(PtrS)){
printf("栈为空\n");
return 0;
}
else{
FirstCell=PtrS->Next;
PtrS->Next=FirstCell->Next;
TopElement=FirstCell->Data;
free(FirstCell);
return TopElement;
}
}
int main()
{
int i;
PtrS=MakeEmpty();
Push(41,PtrS);
printf("%d\n",PtrS->Next->Data);
Push(14,PtrS);
Push(67,PtrS);
Stack S=PtrS;
for(i=0;i<3;i++){
S=S->Next;
printf("%d ",S->Data);
}
printf("\n");
Stack S2=PtrS;
printf("出栈为:%d\n",Pop(S2));
for(i=0;i<2;i++){
S2=S2->Next;
printf("%d ",S2->Data);
}
printf("\n");
return 0;
}