進出棧

很久沒有看多數據結構了,今天遇到一道題,哎!不會啊,

一狠心就寫一遍了!

 

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string>

using namespace std;

#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define LISTINCREMENT 10

typedef struct
{
int * base;
int * top;
int stacksize;
}Sqstack;

int InitStack(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 1;
}
void DisplayStack(Sqstack S)
{
if(S.top == S.base)
cout<<"\t\t\t棧是空棧\n";
int * p;
printf("\t\t\t");
for(p=S.base; p<S.top; p++)
printf("%3d",*p);
cout<<endl;
}
int menu_select()
{
char c;
do {
system("cls");
cout<<"\t\t*************************\n";
cout<<"\t\t     1.入棧     \n";
cout<<"\t\t     2.出棧     \n";
cout<<"\t\t     0.退出     \n";
cout<<"\t\t*************************\n";
cout<<"\t\t給出你的選擇(0-2):";
c = getchar();
}while(c<'0' ||c>'2');

return (c-'0');
}

void Push(Sqstack & S)
{
int n,e;
printf("請輸入此次近棧的元素個數");
cin>>n;
while(n > 0)
{
if(S.top - S.base >=S.stacksize)
{
S.base = (int *)realloc(S.base,(S.stacksize + LISTINCREMENT)*sizeof(int));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += LISTINCREMENT;
}

cout<<"\t\t 請輸入入棧元素:";
cin >> e;
*S.top ++= e;
n --;
}
DisplayStack(S);

}

void Pop(Sqstack &S)
{
int n,e;
if(S.top == S.base)
cout<<"\t\t棧是空棧,無法進行操作!\n";
else
{
cout<<"請輸入此次出棧的元素個數";
cin >>n;
while(n < 1 || n > S.top - S.base)
{
cout<<"輸入有誤,請重新輸入:";
cin>>n;
}

while(n > 0)
{
e = * --S.top;
cout<<"出棧元素是:"<<e<<endl;
n --;
}
}
cout<<"\t\t棧內剩餘元素:\n";
DisplayStack(S);
}
void main()
{
int f;
Sqstack S;
f = InitStack(S);

if(f == 1)
{
for(;;)
{
switch(menu_select())
{
case 1:
cout<<"\t\t\t對於以下元素進行入棧操作!\n";
DisplayStack(S);
Push(S);
cout<<"\t\t\t";
system("pause");
break;
case 2:
cout<<"\t\t\t對於以下元素進行出棧操作\n";
DisplayStack(S);
Pop(S);
cout<<"\t\t\t";
system("pause");
break;

case 0:
cout<<"\t\t\t歡迎使用!\n";
system("pause");
exit(0);
}
   
}
}
}


 

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