1 class Queue { 2 public: 3 stack<int> stack1; 4 stack<int> stack2; 5 6 Queue() { 7 // do intialization if necessary 8 } 9 10 void push(int element) { 11 // write your code here 12 stack1.push(element); 13 } 14 15 int pop() { 16 // write your code here 17 if (stack2.empty()) { 18 while (!stack1.empty()) { 19 int elem = stack1.top(); 20 stack1.pop(); 21 stack2.push(elem); 22 } 23 } 24 int elem = stack2.top(); 25 stack2.pop(); 26 return elem; 27 } 28 29 int top() { 30 // write your code here 31 if (stack2.empty()) { 32 while (!stack1.empty()) { 33 int elem = stack1.top(); 34 stack1.pop(); 35 stack2.push(elem); 36 } 37 } 38 return stack2.top(); 39 } 40 };
时间: 2024-11-06 18:01:23