LeetCode232 Implement Queue using Stacks Java 题解

Implement the following operations of a queue using stacks.

• push(x) -- Push element x to the back of queue.
• pop() -- Removes the element from in front of queue.
• peek() -- Get the front element.
• empty() -- Return whether the queue is empty.
Notes:
• You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is emptyoperations are valid.
• Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
• You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

class MyQueue {
// Push element x to the back of queue.
Stack<Integer> stack=new Stack<>();
Stack<Integer> stack2=new Stack<>();

public void push(int x) {
while(!stack.isEmpty())
{
stack2.push(stack.pop());
}
stack2.push(x);
while(!stack2.isEmpty())
{
stack.push(stack2.pop());
}

}

// Removes the element from in front of queue.
public void pop() {
stack.pop();
}

// Get the front element.
public int peek() {
return stack.peek();
}

// Return whether the queue is empty.
public boolean empty() {
return stack.isEmpty();
}
}

class MyQueue2 {
// Push element x to the back of queue.
Stack<Integer> stack=new Stack<>();
Stack<Integer> stack2=new Stack<>();

public void push(int x) {
while(!stack2.isEmpty())
stack.push(stack2.pop());
stack.push(x);

}

// Removes the element from in front of queue.
public void pop() {

while(!stack.isEmpty())
stack2.push(stack.pop());
stack2.pop();

}

// Get the front element.
public int peek() {
while(!stack.isEmpty())
stack2.push(stack.pop());
return stack2.peek();

}

// Return whether the queue is empty.
public boolean empty() {
while(!stack2.isEmpty())
stack.push(stack2.pop());
return stack.isEmpty();
}
}

2015-05-05 10:04:25

LeetCode 232： Implement Queue using Stacks

2015-07-07 19:35:06

leetcode 232:Implement Queue using Stacks

2015-07-07 04:48:38

Leetcode第二题解题java实现

2015-05-25 10:42:41

232. Implement Queue using Stacks [easy] (Python)

2016-06-04 23:32:59

【LeetCode】Implement Stack using Queues 解题报告

2015-06-14 10:35:53

LeetCode 225: Implement Stack using Queues

2015-06-13 14:58:28

leetcode-232-Implement Queue using Stacks

2017-02-19 10:56:23

Leetcode_232_Implement Queue using Stacks

2015-09-12 11:01:23

【LeetCode-232】 Implement Queue using Stacks(C++)

2016-09-03 17:37:16

不良信息举报

LeetCode232 Implement Queue using Stacks Java 题解