File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ //225 Implement Stack using Queues
2+ public class MyStack {
3+ //1st approach using only one queue
4+ // private Queue<Integer> q;
5+
6+ // public MyStack() {
7+ // q = new LinkedList<>();
8+ // }
9+
10+ // public void push(int x) {
11+ // q.add(x);
12+ // for (int i = 1; i < q.size(); i++) {
13+ // q.add(q.remove());
14+ // }
15+ // }
16+
17+ // public int pop() {
18+ // return q.remove();
19+ // }
20+
21+ // public int top() {
22+ // return q.peek();
23+ // }
24+
25+ // public boolean empty() {
26+ // return q.isEmpty();
27+ // }
28+
29+ //2nd approach
30+ //using 2 queue
31+ private Queue <Integer > q1 ;
32+ private Queue <Integer > q2 ;
33+ public MyStack (){
34+ q1 = new LinkedList <>();
35+ q2 = new LinkedList <>();
36+ }
37+ public void push (int x ){
38+ q2 .add (x );
39+ while (!q1 .isEmpty ()){
40+ q2 .add (q1 .remove ());
41+ }
42+ while (!q2 .isEmpty ()){
43+ q1 .add (q2 .remove ());
44+ }
45+ }
46+ public int pop (){
47+ if (!q1 .isEmpty ())
48+ return q1 .remove ();
49+ return -1 ;
50+ }
51+ public int top (){
52+ if (!q1 .isEmpty ())
53+ return q1 .peek ();
54+ return -1 ;
55+ }
56+ public boolean empty (){
57+ return q1 .isEmpty ();
58+ }
59+ }
60+
61+ /**
62+ * Your MyStack object will be instantiated and called as such:
63+ * MyStack obj = new MyStack();
64+ * obj.push(x);
65+ * int param_2 = obj.pop();
66+ * int param_3 = obj.top();
67+ * boolean param_4 = obj.empty();
68+ */
You can’t perform that action at this time.
0 commit comments