Skip to content

Commit 1f3169a

Browse files
committed
Solution for: Implement stack using queues
1 parent 3001311 commit 1f3169a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package leetcode;
2+
3+
import java.util.LinkedList;
4+
import java.util.Queue;
5+
6+
public class ImplementStackQueues {
7+
public static void main(String[] args){
8+
MyStack stack= new MyStack();
9+
stack.push(1);
10+
stack.push(2);
11+
stack.push(3);
12+
System.out.println(stack.top());
13+
}
14+
}
15+
16+
class MyStack {
17+
Queue<Integer> q = new LinkedList();
18+
/** Initialize your data structure here. */
19+
public MyStack() {
20+
21+
}
22+
23+
/** Push element x onto stack. */
24+
public void push(int x) {
25+
q.offer(x);
26+
int n = q.size()-1;
27+
for(int i=0;i< n;i++){
28+
q.offer(q.poll());
29+
}
30+
}
31+
32+
/** Removes the element on top of the stack and returns that element. */
33+
public int pop() {
34+
return q.poll();
35+
}
36+
37+
/** Get the top element. */
38+
public int top() {
39+
return q.peek();
40+
}
41+
42+
/** Returns whether the stack is empty. */
43+
public boolean empty() {
44+
return q.isEmpty();
45+
}
46+
}

0 commit comments

Comments
 (0)