-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementStackusingQueues_225.java
More file actions
78 lines (69 loc) · 2.48 KB
/
Copy pathImplementStackusingQueues_225.java
File metadata and controls
78 lines (69 loc) · 2.48 KB
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
package Stack_Queue;
import java.util.LinkedList;
import java.util.Queue;
public class ImplementStackusingQueues_225 {
static class MyStack {
Queue <Integer> op1,op2;
/** Initialize your data structure here. */
public MyStack() {
op1=new LinkedList<>();
op2=new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
if(op1.isEmpty()&&op2.isEmpty()) op1.add(x);
else if(op1.isEmpty())
op2.add(x);
else
op1.add(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(op1.isEmpty()&&op2.isEmpty()) throw new NullPointerException();
int data=-1;
if(op1.isEmpty()){
int len=op2.size()-1;//先前没有该句,在在循环中改变了栈的大小,条件又与栈大小相关,导致产生错误
for(int i=0;i<len;i++)
op1.add(op2.poll());
if(op2.size()==1) data=op2.poll();
}else if(op2.isEmpty()) {
int len=op1.size()-1;
for(int i=0;i<len;i++)
op2.add(op1.poll());
if(op1.size()==1) data=op1.poll();
}
return data;
}
/** Get the top element. */
public int top() {
if(op1.isEmpty()&&op2.isEmpty()) throw new NullPointerException();
int data=-1;
if(op1.isEmpty()){
int len=op2.size()-1;
for(int i=0;i<len;i++)
op1.add(op2.poll());
if(op2.size()==1) data=op2.peek();
op1.add(op2.poll());
}else if(op2.isEmpty()) {
int len=op1.size()-1;
for(int i=0;i<len;i++)
op2.add(op1.poll());
if(op1.size()==1) data=op1.peek();
op2.add(op1.poll());
}
return data;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return op1.isEmpty()&&op2.isEmpty();
}
}
public static void main(String[] args) {
MyStack myStack=new MyStack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
int data=myStack.top();
System.out.println(myStack.top());
}
}