Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c5cd383

Browse files
authored
Update _225.java
1 parent a811894 commit c5cd383

File tree

1 file changed

+63
-33
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+63
-33
lines changed
Lines changed: 63 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,67 @@
1-
package com.fishercoder.solutions;
2-
31
import java.util.LinkedList;
42
import java.util.Queue;
53

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+
}
3767
}

0 commit comments

Comments
 (0)