forked from kexun/jianzhioffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay04.java
153 lines (125 loc) · 2.57 KB
/
Day04.java
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package com.offer;
import java.util.LinkedList;
/**
* 两个栈实现队列效果 两个队列实现栈的效果
* @author kexun
*
*/
public class Day04 {
public static void main(String[] args) {
Queue<Integer> queue = new Day04().new Queue<Integer>();
Queue<Integer> queue2 = new Day04().new Queue<Integer>();
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue2.push(55);
queue2.push(66);
queue2.push(77);
while (queue2.hasNext()) {
System.out.println(queue2.poll());
}
while (queue.hasNext()) {
System.out.println(queue.poll());
}
}
static class Main {
public static void main(String[] args) {
Day04 d = new Day04();
Stack<Integer> stack = d.new Stack<>();
stack.addFirst(1);
stack.addFirst(2);
stack.addFirst(3);
stack.addFirst(4);
while (stack.hasNext()) {
System.out.println(stack.pop());
}
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
/**
* 队列的实现
* @author kexun
*
* @param <T>
*/
public class Queue<T> {
private LinkedList<T> first = new LinkedList<>();
private LinkedList<T> second = new LinkedList<>();
/**
* 插入对了
* @param t
*/
public void push(T t) {
first.addFirst(t);
}
/**
* 返回并移除队头
* @return
*/
public T poll() {
if (first.isEmpty() && second.isEmpty()) {
return null;
}
if (second.isEmpty()) {
while (!first.isEmpty()) {
second.addFirst(first.pollFirst());
}
}
return second.pollFirst();
}
public boolean hasNext() {
if (first.isEmpty() && second.isEmpty())
return false;
return true;
}
}
/**
* 两个队列实现栈
* @author kexun
*
* @param <T>
*/
public class Stack<T> {
private java.util.Queue<T> first = new LinkedList<T>();
private java.util.Queue<T> second = new LinkedList<T>();
/**
* 入栈
* @param t
*/
public void addFirst(T t) {
first.offer(t);
}
/**
* 出栈
* @return
*/
public T pop() {
if (second.isEmpty()) {
while (!first.isEmpty()) {
if (first.size() == 1) {
return first.poll();
}
second.offer(first.poll());
}
}
if (first.isEmpty()) {
while (!second.isEmpty()) {
if (second.size() == 1) {
return second.poll();
}
first.offer(second.poll());
}
}
return null;
}
public boolean hasNext() {
if (first.isEmpty() && second.isEmpty())
return false;
return true;
}
}
}