1. 程式人生 > >7 線性表-棧-順序存儲的拓展-迎面增長的存儲方式

7 線性表-棧-順序存儲的拓展-迎面增長的存儲方式

def 註意 pre from cti 可能 main end ||

描述:
設有兩個棧,S1和S2,都采用順序棧的存儲方式。
兩個棧共享一個存儲區:【0,……maxsize-1】
目的:可以盡量利用空間,減少溢出的可能,采用棧頂相向、迎面增長的存儲方式

PS:要註意判斷棧滿棧空的檢查

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define maxsize 100

/*棧結構的定義*/
typedef struct
{
    int stackk[maxsize];
    int top[2];//兩個棧頂指針top[0]指向stackk左端,top[1]指向stackk右端
int length[2]; } stk; /*入棧*/ /*i表示兩個不同的棧,0表示左邊的棧,1表示右邊的棧 左邊的棧每入棧一個元素指針向右移動,右邊的棧每入棧一個元素指針向左移動 入棧操作前要判斷棧是否為滿 */ void initStackk(stk *S) { S->length[0]=0; S->length[1]=0; S->top[0]=-1; S->top[1]=maxsize; } int Push(int i,int x,stk *S) { if(i!=0&&i!=1) { cout
<<"wrong stack number"<<endl; return 0; } else if(S->top[0]==(S->top[1]-1)) { cout<<"the stack is filled with data"; return 0; } if(i==0) { S->stackk[++S->top[0]]=x; S->length[i]++; } else { S
->stackk[--S->top[1]]=x; S->length[i]++; } cout<<"Successful."<<endl; return 1; } int Pop(int i,int &x,stk *S) { if(i!=0&&i!=1) { cout<<"wrong stack number"<<endl; return 0; } if(S->top[i]==-1||S->top[i]==maxsize) { cout<<"Stack"<<i<<" is null."; return 0; } if(i==0) { x=S->stackk[S->top[i]--]; S->length[i]--; } else { x=S->stackk[S->top[i]++]; S->length[i]--; } cout<<"Successful."<<endl; return 1; } void showtheStack(stk *S) { cout<<"Stack0 : "; for(int i=0; i<S->length[0]; i++) cout<<S->stackk[i]<<" "; cout<<endl; cout<<"Stack1 : "; for(int i=maxsize-1,j=0; j<S->length[1]; j++,i--) { cout<<S->stackk[i]<<" "; } cout<<endl; } int main() { stk *S=(stk*)malloc(sizeof(stk)); initStackk(S); cout<<"test function ‘Push‘ by input 5 data."<<endl; int w=5; while(w--) { cout<<"input a data and which stack that you want to save"; int a,b; cin>>a>>b; if(!Push(b,a,S)) { w++; } } showtheStack(S); cout<<"test function ‘Pop‘ by input the stack number."<<endl; w=3; while(w--) { int out=-1; cout<<"input a stack number (0/1):"; int in; cin>>in; if(!Pop(in,out,S)) { w++; } if(out>0) { cout<<"you Pop the data "<<out<<" successful from stack"<<in<<"."<<endl; } } showtheStack(S); return 0; }

7 線性表-棧-順序存儲的拓展-迎面增長的存儲方式