要2个栈公用一个存储空间看来栈顶指针只能从两端开始了
设2个栈为栈1,栈2 ,栈1初始的栈顶指针为-1,栈2的初始栈顶指针为Size
1 #include<test.h> 2 class arraywithtwostack 3 { 4 public: 5 arraywithtwostack(int size) 6 { 7 top[1] = -1; 8 top[2] = size; 9 array = new int[size + 1]; 10 } 11 bool IsEmpty(int index); 12 void Push(int index, int data); 13 void Pop(int index); 14 int top_data(int index); 15 16 private: 17 int top[2];// 用来初始化-1 size 18 int *array; 19 int length; //数组的大小 20 };
1 #pragma once 2 #include"test.h" 3 #include<iostream> 4 #include<assert.h> 5 using namespace std; 6 bool arraywithtwostack::IsEmpty(int index) 7 { 8 assert(index == 1 || index == 2); 9 if (index == 1 && top[1] < 1) 10 { 11 return true; 12 } 13 if (index == 2 && top[2]>length) 14 { 15 return true; 16 } 17 return false; 18 } 19 void arraywithtwostack::Push(int index, int data) 20 { 21 assert(index == 1 || index == 2); 22 if (top[2] - top[1] == 1) 23 { 24 cout << "full" << endl; 25 return; 26 } 27 else 28 { 29 index == 1 ? top[1]++ : top[2]--; 30 array[top[index]] = data; 31 } 32 } 33 void arraywithtwostack::Pop(int index) 34 { 35 assert(index == 1 || index == 2); 36 if (IsEmpty(index)) 37 { 38 cout << "empty"; 39 return; 40 } 41 else 42 { 43 index == 1 ? top[1]-- : top[2]++; 44 } 45 } 46 int arraywithtwostack::top_data(int index) 47 { 48 assert(index == 1 || index== 2); 49 if (IsEmpty(index)) 50 { 51 cout << "empty" << endl; 52 return -1; 53 } 54 return array[top[index]]; 55 } 56 void main() 57 { 58 arraywithtwostack s(5); 59 s.Push(1, 5); 60 s.Push(1, 6); 61 cout<<s.top_data(1); 62 system("pause"); 63 }