|
1 |
| -package com.fishercoder.solutions; |
2 |
| - |
3 | 1 | import java.util.LinkedList;
|
4 | 2 | import java.util.Queue;
|
5 | 3 |
|
6 |
| -public class _225 { |
7 |
| - |
8 |
| - public static class Solution1 { |
9 |
| - class MyStack { |
10 |
| - |
11 |
| - Queue<Integer> q = new LinkedList(); |
12 |
| - |
13 |
| - // Push element x onto stack. |
14 |
| - public void push(int x) { |
15 |
| - q.offer(x); |
16 |
| - for (int i = 1; i < q.size(); i++) { |
17 |
| - q.offer(q.remove()); |
18 |
| - } |
19 |
| - } |
20 |
| - |
21 |
| - // Removes the element on top of the stack. |
22 |
| - public void pop() { |
23 |
| - q.poll(); |
24 |
| - } |
25 |
| - |
26 |
| - // Get the top element. |
27 |
| - public int top() { |
28 |
| - return q.peek(); |
29 |
| - } |
30 |
| - |
31 |
| - // Return whether the stack is empty. |
32 |
| - public boolean empty() { |
33 |
| - return q.isEmpty(); |
34 |
| - } |
35 |
| - } |
36 |
| - } |
| 4 | +public class MyStack { |
| 5 | + public Queue<Integer> queue1; |
| 6 | + public Queue<Integer> queue2; |
| 7 | + public int flag; |
| 8 | + public int size; |
| 9 | + public MyStack() { |
| 10 | + queue1=new LinkedList<Integer>(); |
| 11 | + queue2=new LinkedList<Integer>(); |
| 12 | + flag=1; |
| 13 | + size=0; |
| 14 | + } |
| 15 | + |
| 16 | + public void push(int x) { |
| 17 | + if(flag==1){ |
| 18 | + queue1.offer(x); |
| 19 | + }else{ |
| 20 | + queue2.offer(x); |
| 21 | + } |
| 22 | + size++; |
| 23 | + } |
| 24 | + |
| 25 | + public int pop() { |
| 26 | + int value; |
| 27 | + if(flag==1){ |
| 28 | + while(queue1.size()>1){ |
| 29 | + queue2.offer(queue1.poll()); |
| 30 | + } |
| 31 | + value=queue1.poll(); |
| 32 | + flag=2; |
| 33 | + }else{ |
| 34 | + while(queue2.size()>1){ |
| 35 | + queue1.offer(queue2.poll()); |
| 36 | + } |
| 37 | + value=queue2.poll(); |
| 38 | + flag=1; |
| 39 | + } |
| 40 | + size--; |
| 41 | + return value; |
| 42 | + } |
| 43 | + |
| 44 | + public int top() { |
| 45 | + if(flag==1){ |
| 46 | + while(queue1.size()>1){ |
| 47 | + queue2.offer(queue1.poll()); |
| 48 | + } |
| 49 | + int value=queue1.poll(); |
| 50 | + queue2.offer(value); |
| 51 | + flag=2; |
| 52 | + return value; |
| 53 | + }else{ |
| 54 | + while(queue2.size()>1){ |
| 55 | + queue1.offer(queue2.poll()); |
| 56 | + } |
| 57 | + int value=queue2.poll(); |
| 58 | + queue1.offer(value); |
| 59 | + flag=1; |
| 60 | + return value; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + public boolean empty() { |
| 65 | + return size==0?true:false; |
| 66 | + } |
37 | 67 | }
|
0 commit comments