Two stacks are implemented in an array, and any stack cannot overflow when the array is not filled. The solution is to insert one stack from the beginning and the other from the back, and if you insert an element, the top pointer of the two stack does not meet, which means the array is not full and the stack does not overflow.
#include "stdafx.h"#include <iostream>using namespace STD;structspecial_stack{intcapcity;intLtop,rtop;int* Vals;}; special_stack* Create (intcapacity) {special_stack* Sstack =NewSpecial_stack; Sstack->vals =New int[Capacity]; Sstack->capcity = capacity; Sstack->ltop =-1; Sstack->rtop = capacity;returnSstack;}BOOLLpush (special_stack** Sstack,intVal) {if((*sstack)->ltop +1= = (*sstack)->rtop)return false; (*sstack)->vals[++ ((*sstack)->ltop)] = val;return true;}BOOLLpop (special_stack** Sstack,int& Val) {if((*sstack)->ltop <0)return false; val = (*sstack)->vals[((*sstack)->ltop)--];return true;}BOOLRpush (special_stack** Sstack,intVal) {if((*sstack)->rtop-1= = (*sstack)->ltop)return false; (*sstack)->vals[--((*sstack)->rtop)] = val;return true;}BOOLRpop (special_stack** Sstack,int& Val) {if((*sstack)->rtop >= (*sstack)->capcity)return false; val = (*sstack)->vals[((*sstack)->rtop) + +];return true;}voidDestroy (special_stack** sstack) {Delete[] (*sstack)->vals;Delete(*sstack); *sstack = NULL;}voidClear (special_stack** sstack) {(*sstack)->ltop =-1; (*sstack)->rtop = (*sstack)->capcity;}int_tmain (intARGC, _tchar* argv[]) {special_stack*Stack= Create ( -); for(inti =1; I <=Ten; ++i) {Lpush (&Stack, i); Rpush (&Stack, i +Ten); } for(inti =1; I <=Ten; ++i) {intValif(Lpop (&Stack, Val))cout<<val<<"'; }cout<<endl; for(inti =1; I <=Ten; ++i) {intValif(Rpop (&Stack, Val))cout<<val<<"'; }cout<<endl; for(inti =1; I <=Ten; ++i) {Lpush (&Stack, i); Rpush (&Stack, i +Ten); }cout<<lpush (&Stack, +) <<endl;cout<<rpush (&Stack, to) <<endl;intVal Lpop (&Stack, Val); Rpop (&Stack, Val);cout<<lpush (&Stack, +) <<endl;cout<<rpush (&Stack, to) <<endl; Destroy (&Stack);return 0;}
Topic 16: Implement two stacks in an array