用一个固定的数组实现栈和队列
题目描述:
Problem 1:
用数组结构实现大小固定的栈
解题思路:
给定一个指针即可实现。
代码实现:
1 class ArrayToStack 2 { 3 public: 4 ArrayToStack(int size = 3) 5 { 6 this->size = size; 7 } 8 9 void Push(const int a) 10 { 11 if (ptr < size) 12 arr[ptr++] = a; 13 else 14 cout << "error:the stack is full!" << endl; 15 } 16 17 int Top() 18 { 19 if (ptr > 0) 20 return arr[ptr-1]; 21 else 22 cout << "error:the stack is empty!" << endl; 23 return -1; 24 } 25 26 void Pop() 27 { 28 if (ptr > 0) 29 ptr--; 30 else 31 cout << "error:the stack is empty!" << endl; 32 } 33 34 private: 35 int size; 36 int *arr = new int[size]; 37 int ptr = 0; 38 };
Problem2:
使用数组实现队列和
解题思路:
使用两个指针分别指向队列的前和尾:
代码实现:
1 class ArrayToQueue 2 { 3 public: 4 ArrayToQueue(int size = 3) :N(size) {} 5 6 void Push(int a) 7 { 8 if (size < N) 9 { 10 if (ptr1 >= N) 11 ptr1 = 0; 12 arr[ptr1++] = a; 13 size++; 14 } 15 else 16 cout << "error: the queue is full!" << endl; 17 } 18 19 int Top() 20 { 21 if (size > 0) 22 return arr[ptr0]; 23 else 24 cout << "error: the queue is empty!" << endl; 25 return -1; 26 } 27 28 void Pop() 29 { 30 if (size > 0) 31 { 32 if (ptr0 >= N) 33 ptr0 = 0; 34 ptr0++; 35 size--; 36 } 37 else 38 cout << "error: the queue is empty!" << endl; 39 } 40 41 private: 42 int N; 43 int ptr0 = 0, ptr1 = 0, size = 0; 44 int *arr = new int [N]; 45 46 };
测试代码:
1 void Test() 2 { 3 ArrayToStack s(5); 4 s.Pop(); 5 cout << s.Top() << endl; 6 cout << "****************" << endl; 7 s.Push(1); 8 s.Push(2); 9 s.Push(3); 10 s.Push(4); 11 s.Push(5); 12 s.Push(6); 13 cout << "****************" << endl; 14 cout << s.Top() << endl; 15 s.Pop(); 16 cout << s.Top() << endl; 17 18 19 cout << "==========================" << endl; 20 cout << "==========================" << endl; 21 cout << "==========================" << endl; 22 ArrayToQueue q(5); 23 cout << q.Top() << endl; 24 q.Pop(); 25 26 q.Push(1); 27 q.Push(2); 28 q.Push(3); 29 q.Push(4); 30 q.Push(5); 31 q.Push(6); 32 33 cout << q.Top() << endl; 34 q.Pop(); 35 cout << q.Top() << endl; 36 37 q.Push(6); 38 cout << q.Top() << endl; 39 40 }