顺序栈基本操作代码实现
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <cstdlib>
#define OK 0
#define ERROR -1
#define OVERFLOW -2
#define MAXSIZE 100
typedef int Status;
typedef int SElemType;
typedef struct {
SElemType * base;
SElemType * top;
int stacksize;
} SqStack;
Status InitStack ( SqStack & S)
{
S. base= new int [ MAXSIZE] ;
if ( ! S. base)
{
cout<< "初始化失败" << endl;
return ERROR;
}
else
{
cout<< "初始化成功" << endl;
S. top= S. base;
S. stacksize= 0 ;
return OK;
}
}
Status Push ( SqStack & S, SElemType e)
{
if ( S. top- S. base== MAXSIZE)
return ERROR;
* S. top++ = e;
return OK;
}
Status Pop ( SqStack & S, SElemType & e)
{
if ( S. top== S. base)
return ERROR;
e= * -- S. top;
return OK;
}
Status GetTop ( SqStack S, SElemType & e)
{
if ( S. top== S. base)
return ERROR;
e= * S. top;
return OK;
}
Status StackEmpty ( SqStack & S)
{
if ( S. top == S. base)
return OK;
else
return ERROR;
}
Status GetTop ( SqStack & S)
{
if ( S. top== S. base)
{
cout<< "栈为空,无栈顶元素" << endl;
return ERROR;
}
else
{
cout<< "栈顶元素为" << * ( S. top) << endl;
return OK;
}
}
Status ClearStack ( SqStack & S)
{
S. top= S. base;
cout<< "栈已清空" << endl;
return OK;
}
Status DestoryStack ( SqStack & S)
{
delete ( S. base) ;
S. base= NULL ;
S. top= NULL ;
S. stacksize= 0 ;
cout<< "栈已销毁" << endl;
return OK;
}
Status OutputStack ( SqStack S)
{
cout<< "栈中全部元素为:" ;
for ( int i= 0 ; i< S. stacksize; i++ )
{
int m;
Pop ( S, m) ;
cout<< m<< " " ;
}
cout<< endl;
return 0 ;
}
Status main ( )
{
SqStack S;
int choose= - 1 ;
cout<< "1.初始化栈" << endl;
cout<< "2.销毁栈" << endl;
cout<< "3.清空栈" << endl;
cout<< "4.栈判空" << endl;
cout<< "5.求栈长度" << endl;
cout<< "6.获取栈顶元素" << endl;
cout<< "7.插入一个元素" << endl;
cout<< "8.删除一个元素" << endl;
cout<< "9.输出所有元素" << endl;
cout<< "10.进制转换" << endl;
cout<< "0.退出" << endl;
while ( choose!= 0 )
{
cout<< "请输入选择的功能" << endl;
cin>> choose;
switch ( choose)
{
case 1 :
InitStack ( S) ;
break ;
case 2 :
DestoryStack ( S) ;
break ;
case 3 :
ClearStack ( S) ;
break ;
case 4 :
StackEmpty ( S) ;
break ;
case 5 :
cout<< "栈长度为" << S. stacksize<< endl;
break ;
case 6 :
GetTop ( S) ;
break ;
case 7 :
cout<< "请输入进栈元素:" << endl;
SElemType e;
cin>> e;
S. stacksize++ ;
Push ( S, e) ;
break ;
case 8 :
cout<< endl<< "弹出的栈顶元素为:" << endl;
SElemType t;
Pop ( S, t) ;
cout<< t<< " " << endl;
break ;
case 9 :
OutputStack ( S) ;
break ;
case 10 :
int N, d;
SqStack S1;
InitStack ( S1) ;
cout<< "请输入要转换的数:" << endl;
cin>> N;
cout<< "请输入要转换的进制:" << endl;
cin>> d;
while ( N)
{
Push ( S1, N% d) ;
N= N/ d;
}
cout<< "转换后的数为:" ;
while ( StackEmpty ( S1) )
{
int e;
Pop ( S1, e) ;
cout<< e;
}
cout<< endl;
break ;
case 0 :
break ;
}
}
return 0 ;
}