-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImplementQueueUsingStacks.java
110 lines (87 loc) · 2.5 KB
/
ImplementQueueUsingStacks.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.leetcode.algorithms.easy.queue;
import java.util.Stack;
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
public class ImplementQueueUsingStacks {
public static void main(String...strings) {
MyQueue obj = new MyQueue();
obj.push(1);
obj.push(2);
obj.push(3);
//System.out.println("pop: " + obj.pop());
//System.out.println("pop: " + obj.pop());
//System.out.println("pop: " + obj.pop());
System.out.println("peek: " + obj.peek());
//System.out.println("is empty: " + obj.empty());
}
}
/**
* Queue<Integer> queue = new LinkedList<>();
* queue.poll(); // or queue.remove();
* queue.peek();
* queue.isEmpty();
*/
class MyQueue {
Stack<Integer> stack = new Stack<>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
if(this.stack.isEmpty()) {
this.stack.push(x);
} else {
Stack<Integer> tempStack = new Stack<>();
tempStack.push(x);
int size = this.stack.size();
int count = 0;
while(count < size) {
tempStack.push(this.stack.pop());
++count;
}
// Update stack
while(size > -1) {
this.stack.push(tempStack.pop());
--size;
}
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(this.stack.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
int value = this.stack.get(0);
Stack<Integer> tempStack = new Stack<>();
int size = this.stack.size() - 1;
while(size > 0) {
tempStack.push(this.stack.pop());
--size;
}
// Update stack
this.stack = new Stack<>();
size = tempStack.size();
while(size > 0) {
this.stack.push(tempStack.pop());
--size;
}
return value;
}
/** Get the front element. */
public int peek() {
if(this.stack.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return this.stack.get(0);
}
/** Returns whether the queue is empty. */
public boolean empty() {
return this.stack.isEmpty();
}
}