题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
程序代码:
【方法一】
1 class Solution
2 {
3 public:
4
5 void push(int node) {
6 stack1.push(node);
7
8
9 }
10
11 int pop() {
12 int a;
13 if (stack2.size() <= 0){
14 while (stack1.size()>0){
15 a = stack1.top();
16 stack2.push(a);
17 stack1.pop();
18 }
19 }
20 a = stack2.top();
21 stack2.pop();
22
23 return a;
24
25
26 }
27
28 private:
29 stack<int> stack1;
30 stack<int> stack2;
31 };
【方法二】
1 class Solution
2 {
3 public:
4 int cou = 0;
5 void push(int node) {
6 stack1.push_back(node);
7 stack2.push_back(cou++);
8 }
9
10 int pop() {
11 int i = 0;
12 while (stack2[i] == -1)
13 {
14 i++;
15 }
16 stack2[i] = -1;
17 return stack1[i];
18 }
19
20 private:
21 vector <int> stack1;//存数
22 vector <int> stack2;//地址
23 };
测试用例:
1 int main()
2 {
3 Solution fun;
4 int a[10] = {1,2,3,0,0,4,0,5,0,0};
5 int i;
6 for ( i = 0; i < 10; i++)
7 {
8 fun.push(a[i]);
9 }
10 for ( i = 0; i < 10; i++)
11 {
12 cout << " " << fun.pop() /*<< endl*/;
13 }
14 getchar();
15 return 0;
16 }
本文介绍了一种使用两个栈来实现队列的方法,并提供了两种不同的实现思路及代码示例。第一种方法通过两个标准栈来模拟队列的先进先出特性;第二种方法则利用了向量来模拟栈的操作。
912

被折叠的 条评论
为什么被折叠?



