Skip to content

Commit ef4aea9

Browse files
committed
add queue use stack
1 parent 6727f8f commit ef4aea9

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

implement-queue-using-stacks/README.md

Whitespace-only changes.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class MyQueue {
2+
3+
// should use Deque<Integer> stack in modern java
4+
Stack<Integer> stack = new Stack<>();
5+
6+
// Push element x to the back of queue.
7+
public void push(int x) {
8+
Stack<Integer> rev = new Stack<>();
9+
10+
while(!stack.empty()){
11+
rev.push(stack.pop());
12+
}
13+
14+
rev.push(x);
15+
16+
while(!rev.empty()){
17+
stack.push(rev.pop());
18+
}
19+
}
20+
21+
// Removes the element from in front of queue.
22+
public void pop() {
23+
stack.pop();
24+
}
25+
26+
// Get the front element.
27+
public int peek() {
28+
return stack.peek();
29+
}
30+
31+
// Return whether the queue is empty.
32+
public boolean empty() {
33+
return stack.empty();
34+
}
35+
}

implement-queue-using-stacks/index.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
layout: solution
3+
title: Implement Queue using Stacks
4+
date: 2015-07-07 21:04:46+08:00
5+
leetcode_id: 232
6+
---
7+
{% include_relative README.md %}

0 commit comments

Comments
 (0)