标签:
Implement the following operations of a queue using stacks.
Notes:
push to top
, peek/pop from top
, size
, and is empty
operations are valid.1 class MyQueue { 2 Stack<Integer> stack1; 3 Stack<Integer> stack2; 4 5 public MyQueue() { 6 stack1 = new Stack<Integer>(); 7 stack2 = new Stack<Integer>(); 8 } 9 10 // Push element x to the back of queue. 11 public void push(int x) { 12 stack1.push(x); 13 } 14 15 // Removes the element from in front of queue. 16 public void pop() { 17 stack2 = new Stack<Integer>(); 18 int length = stack1.size(); 19 while (length > 1) { 20 stack2.push(stack1.pop()); 21 length--; 22 } 23 stack1.pop(); 24 length = stack2.size(); 25 while (length > 0) { 26 stack1.push(stack2.pop()); 27 length--; 28 } 29 } 30 31 // Get the front element. 32 public int peek() { 33 stack2 = new Stack<Integer>(); 34 int current = 0; 35 int length = stack1.size(); 36 while (length > 0) { 37 current = stack1.pop(); 38 stack2.push(current); 39 length--; 40 } 41 length = stack2.size(); 42 while (length > 0) { 43 stack1.push(stack2.pop()); 44 length--; 45 } 46 return current; 47 } 48 49 // Return whether the queue is empty. 50 public boolean empty() { 51 return stack1.empty(); 52 } 53 }
Implement Queue using Stacks 解答
标签:
原文地址:http://www.cnblogs.com/ireneyanglan/p/4862802.html