标签:
共享栈,利用栈的动态性使栈空间能够互相补充,存储空间能够得到有效利用
1 #include <iostream> 2 using namespace std; 3 #define stacksize 20 4 typedef struct 5 { 6 int stack[stacksize]; 7 int top[2]; 8 }seqstack; 9 void initstack(seqstack *s) 10 { 11 s->top[0]=-1; 12 s->top[1]=stacksize; 13 } 14 int isempty(seqstack *s) 15 { 16 if(s->top[0]==-1&&s->top[1]==stacksize) 17 return 1; 18 return 0; 19 } 20 int pushstack(seqstack *s,int num,bool flag) 21 { 22 if(s->top[0]==s->top[1]) 23 { 24 cout<<"栈满"<<endl; 25 return 0; 26 } 27 switch(flag) 28 { 29 case 0: /*入左栈*/ 30 s->top[0]++; 31 s->stack[s->top[0]]=num; 32 break; 33 case 1: 34 s->top[1]--; 35 s->stack[s->top[1]]=num; 36 break; 37 default: 38 break; 39 } 40 return 0; 41 } 42 int popstack(seqstack *s,bool flag) 43 { 44 switch(flag) 45 { 46 case 0: 47 if(s->top[0]==-1) 48 { 49 cout<<"空栈"; 50 return 0; 51 } 52 else 53 s->top[0]--; 54 break; 55 case 1: 56 if(s->top[1]==stacksize) 57 { 58 cout<<"空栈"; 59 return 0; 60 } 61 else 62 s->top[1]++; 63 default: 64 break; 65 } 66 } 67 int getstack(seqstack *s,bool flag) 68 { 69 switch(flag) 70 { 71 case 0: 72 if(s->top[0]==-1) 73 { 74 cout<<"空栈"; 75 return 0; 76 } 77 else 78 cout<<s->stack[s->top[0]]<<endl; 79 break; 80 case 1: 81 if(s->top[1]==stacksize) 82 { 83 cout<<"空栈"; 84 return 0; 85 } 86 else 87 cout<<s->stack[s->top[1]]<<endl; 88 break; 89 default: 90 break; 91 } 92 } 93 int main() 94 { 95 seqstack s; 96 initstack(&s); 97 pushstack(&s,1,0); 98 pushstack(&s,2,0); 99 pushstack(&s,3,0); 100 pushstack(&s,9,1); 101 pushstack(&s,8,1); 102 pushstack(&s,7,1); 103 getstack(&s,1); 104 popstack(&s,1); 105 getstack(&s,1); 106 }
标签:
原文地址:http://www.cnblogs.com/a1225234/p/4664749.html