栈是除了线性表的又一线性数据结构,“栈”这一名字形象地表征了这一数据结构的特点,他只能在数据的一端进行操作,即只能在栈顶实现“入栈”和“出栈”。而顺序栈开辟内存空间的方式和顺序表类似,实现顺序栈比较简单。本次实现的操作包括:
- 构造空栈
- 入栈
- 出栈
- 打印从栈底到栈顶的每个元素
#include<stdio.h>
#include<stdlib.h>
#include "malloc.h"
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 5
#define STACKINCREMENT 10
typedef int Status;
typedef struct{
int *top; //栈顶指针
int *base; //栈底指针
int stacksize;
}SqStack;
Status InitStack_Sq(SqStack &S){
//构造空栈
S.base = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
if(!S.base)exit (OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack &S,int e){
//e入栈
if(S.top - S.base >= S.stacksize){
S.base = (int *)realloc(S.base,(S.stacksize + STACKINCREMENT) * sizeof(int));
if(!S.base)exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return OK;
}
Status GetTop(SqStack S,int &e){
//获取栈顶元素
if (S.top == S.base)return ERROR;
e = *(--S.top);
printf("栈顶元素:%d\n",e);
return OK;
}
Status Pop(SqStack &S,int &e){
//删除栈顶元素,用e返回(出栈)
if(S.top == S.base)return ERROR;
e = *(--S.top);
printf("%d被删除了\n",e);
return OK;
}
Status print_sq(SqStack S){
//从栈底到栈顶依次打印每个元素
printf("从栈底到栈顶的元素分别是:\n");
for(int j = 0;j < (S.top - S.base);j++)printf("%d ",*(S.base + j));
printf("\n");
return OK;
}
int main()
{
SqStack S;
int e;
int count, i;
InitStack_Sq(S);
printf("请输入需入栈的元素个数:N = ");
scanf("%d", &count);
printf("请输入元素:");
for (i = 0; i < count; i++)
{
scanf("%d", &e);
Push(S, e);
}
print_sq(S);
GetTop(S,e);
printf("请输入插入栈的元素: ");
scanf("%d", &e);
Push(S, e);
GetTop(S,e);
print_sq(S);
printf("\n演示出栈操作\n");
Pop(S,e);
print_sq(S);
GetTop(S,e);
return 0;
}
所用编译器为dev c++.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。