3.21 Write routines to implement two stacks using only one arrayYour stack routines should not declare an overflow unless everyslot in the array is used
3.21 编写例程以仅使用一个数组实现两个堆栈除非使用了数组中的每个插槽,否则堆栈例程不应声明溢出
typedefint Array; Array arr[10]; int l_top, r_top;
//init arr -1 voidinit() { for (int i = 0; i < 10; i++) { arr[i] = -1; } l_top = -1, r_top = 10; }
voidexam() { //print arr printf("["); for (int i = 0; i < 9; i++) { printf("%d ", arr[i]); } printf("%d]\n", arr[9]); if (l_top >= r_top) { printf("Stack overflow!\n"); } else { printf("Stack not overflow!\n"); } }
intmain() { init(); //e.g.1 pop 3 numbers from left,and pop 7 numbers from right printf("---e.g.1---\n"); for (int i = 0; i < 3; i++) { arr[++l_top] = 233; exam(); } for (int i = 0; i < 7; i++) { arr[--r_top] = 666; exam(); } init(); //e.g.2 pop 3 numbers from left,and pop 8 numbers from right printf("---e.g.2---\n"); for (int i = 0; i < 3; i++) { arr[++l_top] = 233; exam(); } for (int i = 0; i < 8; i++) { arr[--r_top] = 666; exam(); } return0; }