#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 5
#define LEN sizeof(SqStack)
typedef struct
{
int data[MAXSIZE];
int top;
}SqStack;
SqStack *S;
void InitStack()
{
S = (SqStack*)malloc(LEN);
if(!S)
{
perror("malloc");
exit(1);
}
S -> top = -1;
}
void Push()
{
int e;
printf("Please input value:");
scanf("%d",&e);
if(S -> top == MAXSIZE - 1)
{
printf("Stack Full!\n");
}
(S -> top)++;
printf("S -> top = %d\n",S -> top);
S -> data[S -> top] = e;
}
void Pop()
{
if(S -> top == -1)
printf("Stack NULL!\n");
S -> top--;
}
int ClearStack()
{
S -> top = -1;
return 1;
}
void StackEmpty()
{
if(S -> top == -1)
printf("StackEmpty!\n");
else
printf("Stack Not Empty!\n");
}
void StackLength()
{
printf("length = %d\n",S -> top + 1);
}
void DestroyStack()
{
S -> top = -1;
free(S);
S = NULL;
}
void GetTop()
{
if(S -> top == -1)
{
printf("Top NULL!\n");
}
else
{
printf("topdata = %d\n",S -> data[S -> top]);
}
}
void StackTraverse()
{
int i = S -> top;
printf("S -> top = %d\n",S -> top);
while(i != -1)
{
printf("stackdata = %d\n",S -> data[i]);
i--;
}
}
int main()
{
int n;
while(1)
{
printf("1.Init 2.Push 3.Pop 4.Clear 5.Empty 6.Length\n 7.Destroy 8.GetTop 9.Print 10.Exit\n");
printf("Please input num:");
scanf("%d",&n);
switch(n)
{
case 1:InitStack();break;
case 2:Push();break;
case 3:Pop();break;
case 4:ClearStack();break;
case 5:StackEmpty();break;
case 6:StackLength();break;
case 7:DestroyStack();break;
case 8:GetTop();break;
case 9:StackTraverse();break;
}
if(n == 10)
break;
}
return 0;
}
栈的基本操作
最新推荐文章于 2022-01-20 22:43:49 发布