栈
本周学了栈,栈是一种比较基础的数据结构。特点是先进后出,想象自己做公交车,你先上了车走到了公交车的最后面,车上站满了人,要下车的时候,后来上车的人却能先下车。
栈在很多问题上有用处,比如计算字符串的值等等。
接下来使用c语言实现的几个栈的功能。
首先是 数据结构
typedef int ElemType;
typedef struct{
ElemType elem[MAXSIZE];
int top;
}SqStack;
初始化
void InitStack(SqStack *p){
p->top=0;
}
栈添加元素
void Push(SqStack *p,ElemType x){
if(p->top<MAXSIZE-1){
p->top++;p->elem[p->top]=x;
}
else
printf("\n Overflow");
}
栈释放元素
ElemType Pop(SqStack *p){
ElemType x;
if(p->top!=0){
x=p->elem[p->top];
p->top--;
return x;
}
else{
printf("\n Underflow");
return -1;
}
}
获得栈顶元素
ElemType GetTop(SqStack p){
ElemType x;
if(p.top!=0){
x=p.elem[p.top];
return x;
}
else{
printf("\n Underflow");
return -1;
}
}
输出栈内元素
void OutStack(SqStack p){
int i,j;
if(p.top==0)
printf("\n The Stack is NULL.");
for(i=p.top;i>0;i--)
printf("\n %2d %6d",i,p.elem[i]);
}
最后是 主函数
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct{
ElemType elem[MAXSIZE];
int top;
}SqStack;
void OutStack(SqStack p);
void InitStack(SqStack *p);
void Push(SqStack *p,ElemType x);
ElemType Pop(SqStack *p);
ElemType GetTop(SqStack p);
int main(int argc, char *argv[])
{
SqStack q;
int i;
int y;
int cord;
ElemType a;
do{
printf("\n");
printf("\n 主菜单");
printf("\n 1 初始化顺序栈 \n");
printf("\n 2 插入一个元素 \n");
printf("\n 3 删除栈顶元素 \n");
printf("\n 4 取出栈顶元素 \n");
printf("\n 5 结束程序运行 \n");
printf("\n----------------------\n");
printf("输入你的选择(1,2,3,4,5)");
scanf("%d",&cord);
switch(cord)
{
case 1:{
InitStack(&q);
OutStack(q);
}break;
case 2:{
printf("\n 请输入要插入的数据 a=");
scanf("%d",&a);
Push(&q,a);
OutStack(q);
}break;
case 3:{
a=Pop(&q);
printf("\n a=%d",a);
OutStack(q);
}break;
case 4:{
y=GetTop(q);
printf("\n y=%d",y);
OutStack(q);
}break;
case 5:exit(0);
}
}while(cord<=5);
return 0;
}