目录
顺序栈的介绍
顺序栈是指利用顺序存储结构实现的栈,即利用一组地址连续的存储单元依次存放自栈低到栈顶的数据元素,同时设置指针top指向栈顶元素在顺序站的位置,本篇介绍顺序栈的做法是将top指针先指向-1表示空栈,当需要进栈的时候top指针往后移动再放入数据,达到指针每次都是指向栈顶元素的效果。
提示:以下是本篇文章正文内容,下面案例可供参考
一、实现顺序栈的基本操作
- 定义顺序栈
- 构建顺序栈(初始化顺序栈)
- 顺序栈的判空
- 顺序栈的入栈
- 顺序栈的出栈
- 读取顺序栈的栈顶元
二、各操作的代码详解
1.定义顺序栈
代码如下(示例):
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAX 100
typedef struct SeqStack{
int * data;
int top; //栈顶指针
}SeqStack;
2.构建顺序栈
代码如下(示例):
void Initstack(SeqStack * L){
L->top=-1;
L->data=(int *)malloc(sizeof(int)*MAX);
}
3.顺序栈的判空
代码如下(示例):
bool EmptyStack(SeqStack * L){
if(L->top==-1)
{
printf("当前栈空,请加入元素\n");
return false;
}
else
return true;
}
4.顺序栈的入栈
代码如下(示例):
void Push(SeqStack * L ,int pushData){
if(L->top==MAX-1)
return;
L->top++;
L->data[L->top]=pushData;
printf("元素进栈成功\n");
}
5.顺序栈的出栈
代码如下(示例):
int Pop(SeqStack * L){
int popData;
if(EmptyStack(L)==false)
return;
else{
popData=L->data[L->top];
printf("当前出栈元素为:%d\n",popData);
L->top--;
return popData;
}
}
6.读取顺序栈的栈顶元素
代码如下(示例):
int GetTop(SeqStack * L){
int topData;
if(EmptyStack(L)==false)
return;
else{
topData=L->data[L->top];
printf("当前栈顶元素为:%d \n",topData);
return topData;
}
}
总代码
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAX 100
typedef struct SeqStack{
int * data;
int top; //栈顶指针
}SeqStack;
void Menu(){
printf("\n");
printf("\t\t\t\t\t\t --顺序栈的实现--\n");
printf("\t\t\t\t\t\t 1.元素进栈\n");
printf("\t\t\t\t\t\t 2.元素出栈\n");
printf("\t\t\t\t\t\t 3.创建顺序栈表\n");
printf("\t\t\t\t\t\t 4.查找栈顶元素\n");
printf("\t\t\t\t\t\t 0.退出\n");
}
bool EmptyStack(SeqStack * L){
if(L->top==-1)
{
printf("当前栈空,请加入元素\n");
return false;
}
else
return true;
}
void Initstack(SeqStack * L){
L->top=-1;
L->data=(int *)malloc(sizeof(int)*MAX);
}
void Push(SeqStack * L ,int pushData){
if(L->top==MAX-1)
return;
L->top++;
L->data[L->top]=pushData;
printf("元素进栈成功\n");
}
int Pop(SeqStack * L){
int popData;
if(EmptyStack(L)==false)
return;
else{
popData=L->data[L->top];
printf("当前出栈元素为:%d\n",popData);
L->top--;
return popData;
}
}
int GetTop(SeqStack * L){
int topData;
if(EmptyStack(L)==false)
return;
else{
topData=L->data[L->top];
printf("当前栈顶元素为:%d \n",topData);
return topData;
}
}
int main()
{
SeqStack L;
Initstack(&L);
int popData,pushData,topData;
int command;
Menu();
do{
scanf("%d",&command);
switch(command){
case 1:printf("请输入需要入栈的整数:\n");
scanf("%d",&pushData);
Push(&L,pushData);
break;
case 2:popData=Pop(&L);
break;
case 3:Initstack(&L);
printf("创建成功\n");
break;
case 4:topData=GetTop(&L);
break;
case 0:printf("退出成功");
break;
default :printf("输入错误,请重新输入 >");
break;
};
}while(command);
return 0;
}