-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm_1
More file actions
86 lines (64 loc) · 1.73 KB
/
algorithm_1
File metadata and controls
86 lines (64 loc) · 1.73 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
79
80
81
82
83
84
85
86
## 使用2个队列实现栈 ##
class MyStack {
Queue[] q = new LinkedBlockingQueue[2];
// 记录非空队列的脚标
int index = -1;
public MyStack() {
this.q[0] = new LinkedBlockingQueue();
this.q[1] = new LinkedBlockingQueue();
}
public void push(Object element) {
if (index == -1) {
q[0].add(element);
index = 0;
} else {
q[index].add(element);
}
}
public Object pop() {
if (index == -1) {
System.out.println("Task is empty !");
return null;
} else {
while (q[index].size() > 1) {
q[1-index].add(q[index].poll());
}
Object item = q[index].poll();
if (q[1- index].isEmpty()) {
index = -1;
} else {
index = 1 - index;
}
return item;
}
}
public int size() {
return q[index].size();
}
}
## 使用2个栈实现队列 ##
class MyQueue {
Stack orderedStack = new Stack();
Stack reverseStack = new Stack();
public void add(Object element) {
reverseStack.push(element);
}
public Object poll() {
if (!orderedStack.isEmpty()) {
return orderedStack.pop();
} else {
while (!reverseStack.isEmpty()) {
orderedStack.push(reverseStack.pop());
}
if (orderedStack.isEmpty()) {
System.out.println("Queue is empty !");
return null;
} else {
return orderedStack.pop();
}
}
}
public int size() {
return orderedStack.size() + reverseStack.size();
}
}