栈是一种先进后出的结构
可利用数组来构造一个顺序栈
首先定义栈的结构
包含三个部分 :
top值用于指示栈顶元素的上一个内存单位
用来存放栈值的数组
指向栈结构的指针
最先开始编写的代码遇到的问题:
初始定义函数的参数没有用指针,导致在主函数内的相关值并未改变。即在initstack调用后,cout<<a.top不为0,而为一个任意值。
犯了一个经典错误:全局变量的值在局部函数内无法改变。
struct stack{
elementtype top;
elementtype st[stacksize];
stack *p;
};
void initstack(stack a){
a.p=new stack [100];
a.top=0;
if(!a.p)cout<<"errow";
else cout<<"successfully create";
}在这里插入代码片
后经过改变,将局部函数的参数变为指针,即可较好的完成任务。
#include<iostream>
using namespace std;
typedef int elementtype;
#define stacksize 100
int increase=100;
//顺序栈的实现 (top标志指向栈顶元素上一个单位)
struct stack{
elementtype top;
elementtype st[stacksize];
stack *p;
};
void initstack(stack *a){
a->p=new stack [100];
a->top=0;
if(!a->p)cout<<"errow";
else cout<<"successfully create";
}
bool push(stack *a,elementtype e){
if(a->top>=100){
cout<<"overflow,realloc sapce"<<endl;
stack *newp=new stack [stacksize+increase];
if(!newp)cout<<"fail"<<endl;
else cout<<"please Re-operate all the instrution"<<endl;
delete []a->p;
a->p=newp;
}
a->st[a->top]=e;
(a->top)++;
cout<<a->top;
return true;
}
elementtype pop(stack *a){
elementtype e;
if(a->top<=0)cout<<"errow,the satck is empty"<<endl;
else{
(a->top--);
e=a->st[a->top];
return e;
}
}
bool destroy(stack *a){
delete []a->p;
cout<<"successfully destroy the stack"<<endl;
return true;
}
elementtype gettop(stack *a){
elementtype e;
if(a->top<=0)cout<<"the stack is empty"<<endl;
else{
e=a->st[(a->top)-1];
return e;
}
}
bool showstack(stack *a){
elementtype e;
int i=(a->top)-1;
for(;i>=0;i--){
e=a->st[i];
cout<<e<<" ";
}
if(i<0) cout<<"the end"<<endl;
return true;
}
int main(){
stack sta;
stack *s=&sta;
int op=1;
elementtype e;
while(op){
system("cls");
cout<<"………………………………链表操作……………………………………"<<endl;
cout<<"1 创建栈 2 销毁栈 "<<endl;
cout<<"3 入栈 4 出栈 "<<endl;
cout<<"5 输出栈 6 栈顶元素 "<<endl;
cout<<"请输入想要操作功能前的数字"<<endl;
cout<<"输入0退出"<<endl;
cin>>op;
switch(op){
case 1:
initstack(s);
getchar();getchar();
break;
case 2:
destroy(s);
getchar();getchar();
break;
case 3:
cout<<"please enter the element you want to push"<<endl;
cin>>e;
push(s,e);
getchar();getchar();
break;
case 4:
e=pop(s);
cout<<"the element pop out is "<<e<<endl;
getchar();getchar();
break;
case 5:
showstack(s);
getchar();getchar();
break;
case 6:
e=gettop(s);
cout<<"the topelement is "<<e<<endl;
getchar();getchar();
break;
case 0:
break;
}
}
return 0;
}