I. Question
Use an array a [1 .... n] implement two stacks. Unless each unit of the array is used, the stack routine cannot overflow. Note that the time for push and pop operations should be O (1 ).
Ii. Solution
For an array, the two ends of the array serve as the bottom of the stack, and the stack is extended to the middle of the array. When each element in the array is used, the stack is full.
Iii. Code
Struct node; typedef node * comstack; struct node {int capacity; int topl; int topr; elementtype * array ;}; comstack creatcomstack (INT maxelements); int isempty_l (comstack S ); int isempty_r (comstack S); int isfull (comstack S); void makeempty (comstack S); void push_l (elementtype X, comstack S); void push_r (elementtype X, comstack S); elementtype pop_l (comstack S); elementtype pop_r (comstack S ); Void disposecomstack (comstack S); comstack creatcomstack (INT maxelements) {comstack s; S = (comstack) malloc (sizeof (struct node); If (S = NULL) {printf ("out of space"); return NULL;} s-> array = (elementtype *) malloc (sizeof (elementtype) * maxelements ); if (S-> array = NULL) {printf ("out of space"); return NULL;} s-> capacity = maxelements; makeempty (s); Return s ;} int isempty_l (C Omstack s) {If (S-> topl =-1) return true; else return false;} int isempty_r (comstack S) {If (S-> topr = s-> capacity) return true; else return false;} int isfull (comstack S) {If (S-> topl + 1 = s-> topr) return true; else return false;} void makeempty (comstack s) {S-> topl =-1; s-> topr = s-> capacity; // capacity outside the array} void push_l (elementtype X, comstack s) {If (isfull (s) printf ("sta CK is full "); else {S-> topl ++; s-> array [S-> topl] = x ;}} void push_r (elementtype X, comstack S) {If (isfull (s) printf ("Stack is full"); else {S-> topr --; s-> array [S-> topr] = x ;}} elementtype pop_l (comstack s) {elementtype tmpcell; If (isempty_l (s) printf ("Left stack is empty "); else {tmpcell = s-> array [S-> topl]; S-> topl --;} return tmpcell;} elementtype pop_r (comstack s) {elementt Ype tmpcell; If (isempty_r (s) printf ("right stack is empty"); else {tmpcell = s-> array [S-> topr]; s-> topr ++;} return tmpcell;} void disposecomstack (comstack s) {If (s! = NULL) {free (S-> array); free (s );}}
Introduction to algorithms 10.1-2 use an array to implement two stacks