栈的基本操作

编写一个程序,实现顺序栈、链栈各种基本运算并编写主程序分别举例验证这些基本操作:

(1)初始化栈;

(2)判断栈是否为空;

(3)进栈操作;

(4)求栈的长度;

(5)输出栈中的所有的元素;

(6)出栈操作;

(7)释放栈。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define TURE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int SElemType;
using namespace std;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//初始化栈
Status InitStack(SqStack &S)
{//构造一个空栈
S.base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return  OK;
}
//判断栈是否为空
Status GetTop(SqStack &S,SElemType &e)
{
//若栈不空,则用e返回s的栈顶元素,并返回OK;否则返回ERROR;
if(S.top==S.base) return ERROR;
return OK;
}
//入栈
Status Push(SqStack &S,SElemType e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT) * sizeof(SElemType));
if(!S.base) exit (OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}
//求栈的长度
int Stacklength(SqStack &S)
{
if(S.top==S.base) return ERROR;
else
    return S.top-S.base;
}
//输出栈中的所有元素
void Display(SqStack &S)
{
if(S.top==S.base) return ;
else
printf("%d\n",*(--S.top));
}
//出栈
Status Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base) return ERROR;
e=* --S.top;
return OK;
}
//释放栈
void ClearStack(SqStack &S)
{//置空栈
 S.top=S.base;
}
int main()
{
SqStack S;
int i;
SElemType e;
InitStack(S);
printf("构建栈成功\n");
scanf("%d",i);
while(i)
{
switch(i)
{
case 1:Push(S,e); break;
case 2: Pop(S,e);break;
case 3:ClearStack(S);break;
case 4:GetTop(S,e);break;
case 5: Display(S);break;
case 6:Stacklength(S);break;
}
printf("再次操作\n");
scanf("%d",&i);
}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章