顺序栈的基本操作
- 格式:doc
- 大小:40.00 KB
- 文档页数:5
#include<iostream.h>
#include<conio.h>
#define StackSize 100
using namespace std;
typedef char StackData;
typedef struct { //顺序栈定义
StackData data[StackSize]; //栈数组
int top; //栈顶指针
} SeqStack;
void menu()
{
printf("\t--------------------------------------------\n");
printf("\t* *\n");
printf("\t* 1..........CreatStack *\n");
printf("\t* *\n");
printf("\t* 2..........InitStack *\n");
printf("\t* *\n");
printf("\t* 3..........IsEmpty *\n");
printf("\t* *\n");
printf("\t* 4..........IsFull *\n");
printf("\t* *\n");
printf("\t* 5..........PushStack *\n");
printf("\t* *\n");
printf("\t* 6..........PopStack *\n");
printf("\t* *\n");
printf("\t* 7..........Gettop *\n");
printf("\t* *\n");
printf("\t* 0..........exit *\n");
printf("\t* *\n");
printf("\t--------------------------------------------\n");
printf("\t");
}
void CreatStack ( SeqStack *S)//建立栈
{
S->top = -1; //置空栈
}
int InitStack(SeqStack *S)//初始化栈
{
cout<<"\n\n\t\t.....1.Init the stack from the keyboard "<<endl;
cout<<"\n\n\t\t.....2.Return"<<endl;
int q;
char c;
cin>>q;
if(q==2)
{
return 0;
}
if(q==1)
{
int i,n;
cout<<"please input the number of the datas:";
cin>>n;
if(n<=100)
{
cout<<"please input the data:"<<endl;
for(i=0;i<n;i++) //读入元素
{
cin>>S->data[i];
S->top++;
}
S->data[n]='\0';
cout<<endl<<"OK!!"<<endl;
S->top-1;
return 1;
}
else
{
cout<<"OVERFLOW!"<<endl;
return 0;
}
}
}
int StackEmpty (SeqStack *S) //判断栈空
{
return S->top == -1; //判断栈是否空?空则返回1,否则返回0
}
int StackFull (SeqStack *S)//判断栈满
{
return S->top == StackSize-1; //判断栈是否满?满则返回1,否则返回0 }
int Push (SeqStack *S, StackData x)//压栈
{
char c;
cout<<"please write a data you want:";
cin>>c;
if ( StackFull (S) )
{
cout<<"The stack is full.";
}
else
{
x=c;
S->data[++S->top] = x; //加入新元素
cout<<S->data<<endl;
cout<<"Successfully!!"<<endl;
return 1;
}
}
int pop (SeqStack *S, StackData &x)//出栈
{
if ( StackEmpty(S) )
{
cout<<"The stack is empty.";
}
else
{
x = S->data[S->top--];
cout<<x<<endl;
cout<<"Successfully!!"<<endl;
return 1;
}
}
int Gettop (SeqStack *S, StackData &x)// 取栈顶元素
{
if ( StackEmpty(S) ) //若栈空返回0, 否则栈顶元素读到x并返回1 {
cout<<"The stack is empty.";
}
else
{
x = S->data[S->top];//x是头指针的元素
cout<<x<<endl;
cout<<"Successfully!!"<<endl;
return 1;
}
}
int main()
{
SeqStack *S;
int m=1;
StackData x;
while(m>0)
{
menu();
cout<<"please choose from '0' to '7'....."<<endl;
cin>>m;
switch(m)
{
case 1:CreatStack(S);
cout<<"The Stack has been created already!!";
getch();
system("cls");
break;
case 2: InitStack(S);
getch();
system("cls");
break;
case 3: if(StackEmpty(S))
{
cout<<"The stack is empty.";
}
else
{
cout<<"The stack is not empty.";
}
getch();
system("cls");
break;
case 4: if(StackFull(S))
{
cout<<"The stack is full.";
}
else
{
cout<<"The stack is not full.";
}
getch();
system("cls");
break;
case 5: Push(S,x);
getch();
system("cls");
break;
case 6: pop(S,x);
getch();
system("cls");
break;
case 7: Gettop(S,x);
getch();
system("cls");
break;
case 0: exit(0);
default:
continue;
}
}
return 0;
}。