栈是一种特殊的线性表,因此可以用线性表的方法来存储栈。最简单的方法就是用一维数组来存储。由于栈底固定不变的,而栈顶随进出栈操作动态变化的,因此为了实现对的栈的操作,必须记住栈顶的当前位置。
顺序栈优缺点:
优点:简单、存储密度高。
确定:即使栈的长度很长,也还是可能发生上溢。当栈的容量不固定时,必须设置栈的长度以使其可以容纳更多的元素,容易浪费空间。
#include<iostream>
#include<cstdio>
using namespace std;
const int Maxsize=1000;
typedef struct node{
int top;///栈顶
int elements[Maxsize];///栈的容量
}ST;
void SetNull(ST *S){
S->top=-1;
}
bool Is_Empty(ST *S){
if(S->top<0)
return true;
else
return false;
}
ST *ST_Push(ST *S,int x){///入栈
if(S->top>=Maxsize){///上溢现象
cout<<"Stack overflow"<<endl;
return NULL;
}
else{
S->top++;
S->elements[S->top]=x;
return S;
}
}
int ST_Pop(ST *S){ ///根据要求设计返回值类型
if(Is_Empty(S)){
cout<<"Stack underflow"<<endl;///下溢
return NULL;
}
else
{
S->top--;
int element=S->elements[S->top+1];
return element;
}
}
int GET_TOP_Element(ST *S){///获取栈顶元素
if(Is_Empty(S)){
cout<<"Stack underflow"<<endl;///下溢
return NULL;
}
else{
int element=S->elements[S->top];
return element;
}
}
int main()
{ int n;
ST *S=(ST*)malloc(sizeof(ST));
SetNull(S);
cin>>n;
for(int i=1;i<=n;i++)
ST_Push(S,i);
for(int i=3;i<=n;i++)
cout<<ST_Pop(S)<<" ";
cout<<endl;
cout<<GET_TOP_Element(S)<<endl;
return 0;
}
对于顺序栈来说,其实最大的缺点是:当栈的容量不固定时,必须设置栈,使其容纳最多的数据元素,这样会浪费很对存储空间,也可能产生上溢出现象,采用链式存储结构就不会产生类似的问题。
栈的链式存储结构称为链栈,他是运算受限的单链表,其插入和删除只能在表头进行。
#include<iostream>
#include<cstdio>
using namespace std;
typedef struct node{
int va;
struct node *next;
}s,*link_ST;
bool Set_NULL(link_ST &S){///初始化栈
S=NULL;
return true;
}
void PushL(link_ST &S,int data){///入栈
link_ST p=(link_ST)malloc(sizeof(link_ST));
p->va=data;
p->next=S;
S=p;
}
int PopL(link_ST &S){///出栈
if(S==NULL)
cout<<"this if underfloor"<<endl;
else{
link_ST temp=(link_ST)malloc(sizeof(link_ST));
temp->va=S->va;
temp=S;
S=S->next;
return temp->va;
free(temp);
}
}
int GET_TOPelement(link_ST S){///获取栈顶元素
if(S==NULL)
cout<<"this is underfloor"<<endl;
else{
return S->va;
}
}
int main()
{
int n,i;
cin>>n;
link_ST S;
Set_NULL(S);
for(i=1;i<=n;i++)
PushL(S,i);
cout<<"获取当前栈顶元素:";
cout<<GET_TOPelement(S)<<endl;///入栈
cout<<"依次出栈:";
for(i=1;i<=n;i++)
cout<<PopL(S)<<" ";//出栈
cout<<endl;
return 0;
}