本实验来源于姥姥主编《数据结构(第2版)》.
内容也没有很难,就是按照一般初学者听课的视角去敲代码,千里之行始于足下。
//堆栈的顺序存储
#include
#include
#define ERROR -1
typedef int Position;
typedef struct SNode *PtrToStack;
typedef int ElementType;
struct SNode{
ElementType *Data;
Position Top;
int MaxSize;
};
typedef PtrToStack Stack;
Stack CreateStack(int MaxSize);//生成空堆栈,其最大长度为Maxsize
int IsFull(Stack S);//判断堆栈S是否已满
int Push(Stack S,ElementType X);//将元素item压入堆栈
int IsEmpty(Stack S);//判断堆栈S是否为空
ElementType Pop(Stack S);//删除并返回栈顶元素
Stack CreateStack(int MaxSize){
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Data = (ElementType *)malloc(MaxSize*sizeof(ElementType));
S->Top = -1;
S->MaxSize = MaxSize;
return S;
}
int IsFull(Stack S){
return (S->Top==S->MaxSize-1);
}
int Push(Stack PtrS,ElementType X)
{
if(IsFull(PtrS)){
printf("堆栈满");
return ERROR;
}else{
PtrS->Data[++(PtrS->Top)] = X;
return PtrS->Data[PtrS->Top];
}
}
int IsEmpty(Stack S){
return (S->Top==-1);
}
ElementType Pop(Stack PtrS)
{
if(PtrS->Top==-1){
printf("堆栈空");
return ERROR;
}else{
return (PtrS->Data[(PtrS->Top)--]);
}
}
int main()
{
Stack S1 = CreateStack(5);;
int m,full,empty;
full = IsFull(S1);
empty = IsEmpty(S1);
if (full)
printf("Stack is Full:\n");
else
printf("Stack is not Full\n");
if (empty)
printf("Stack is Empty\n");
else
printf("Stack is not Empty\n");
m = Push(S1,1);
m = Push(S1,2);
m = Push(S1,3);
printf("%d\n",m);
full = IsFull(S1);
empty = IsEmpty(S1);
if (full)
printf("Stack is Full:\n");
else
printf("Stack is not Full\n");
if (empty)
printf("Stack is Empty\n");
else
printf("Stack is not Empty\n");
m = Pop(S1);
printf("%d\n",m);
return 0;
}
如果编码的时候,身边有纸笔的话,就更容易将代码牢牢记住了!加油,数据结构被视为计算机的老大哥!
标签:int,S1,PtrS,顺序存储,源码,printf,Top,C语言,Stack
来源: https://blog.csdn.net/m0_37149062/article/details/104864005