栈的顺序存储称顺序栈,图示:
.h文件
//顺序栈
#define MaxSize 5
#define ElemType int
typedef struct
{
ElemType data[MaxSize];
ElemType top; //栈顶指针
}Stack;
//函数声明
Stack InitStack(); //初始化一个栈(顺序栈为新建,与链栈不同)
bool StackEmpty(Stack *p) ; //判断栈空
void Push(Stack *p,ElemType x); //进栈
ElemType Pop(Stack *p); //出栈
ElemType GetTop(Stack *p); //读栈顶元素
void ClearStack(Stack *p); //销毁栈
void PrintStack(Stack *p); //打印栈
.c文件
// 顺序栈
#include "double_node.h"
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n=1;
Stack s;
s=InitStack();
PrintStack(&s);
while(n!=0)
{
printf("\t\t/\n");
printf("\t\tinput your choice \n");
printf("\t\t1.push stack \n");
printf("\t\t2.pop stack \n");
printf("\t\t/\n");
scanf("%d",&n);
switch(n)
{
int m;
case 1: printf("1.input the elem you want to push\n");
scanf("%d",&m);
Push(&s,m);
PrintStack(&s);
break;
case 2: int p=Pop(&s);
printf("pop the numble: %d \n",p);
break;
default:
break;
}
}
return 0;
}
Stack InitStack() //初始化一个栈
{
Stack s;
s.top =0;
int n,m;
printf("input the numble of elem you want to add\n");
scanf("%d",&n);
printf("input the elem \n");
for(int i=0;i<n;i++)
{
scanf("%d",&m);
s.data[i]=m;
}
s.top=n-1;
return s;
}
bool StackEmpty(Stack *p) //判断栈空
{
if(p->top == -1)
{
return true;
}else {
return false;
}
}
void PrintStack(Stack *p) //打印栈
{
int length = p->top;
printf("printf\n");
for(int i=0;i<=length;i++)
{
printf("%d ",p->data[i]);
}
printf("\n");
}
void Push(Stack *p,ElemType x) //进栈
{
int top =p->top;
//判断栈是否为满
if(top!=MaxSize-1)
{
p->data[top+1]=x;
p->top++;
} else{
printf("the Stack is full!\n");
}
}
ElemType Pop(Stack *p) //出栈
{
//判断栈是否为空
if(StackEmpty(p)==true)
{
printf("the stack is empty!\n");
return NULL;
}else return p->data[p->top--];
}
ElemType GetTop(Stack *p) //读栈顶元素
{
//判断栈是否为空
if(StackEmpty(p)==true)
{
printf("the stack is empty!\n");
return NULL;
}else return p->data[p->top];
}
//void ClearStack(Stack *p); //销毁栈