-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathEx_1_3_38_2.java
100 lines (86 loc) · 1.77 KB
/
Ex_1_3_38_2.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
package Ch_1_3;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by HuGuodong on 2019/7/27.
*/
public class Ex_1_3_38_2 {
public static class LinkedListBasedGeneralQueue<Item> {
Node first;
Node last;
int N;
public void insert(Item item) {
Node oldlast = last;
last = new Node(item);
if (oldlast == null) {
first = last;
} else {
oldlast.next = last;
}
N++;
}
public Item delete(int k) {
if (isEmpty()) {
return null;
}
if (k < 1 || k > N) {
throw new IllegalArgumentException("wrong k!");
}
// if remove first
if (k == 1) {
return removeFront();
}
// if k is not first
Node prev = first;
int cnt = 1;
while (++cnt < k) {
prev = prev.next;
}
Item item = prev.next.item;
prev.next = prev.next.next;
N--;
if (isEmpty()) {
last = null;
}
return item;
}
private Item removeFront() {
if (isEmpty()) {
return null;
}
Item item = first.item;
first = first.next;
N--;
if (isEmpty()) {
last = null;
}
return item;
}
public int size() {
return N;
}
public boolean isEmpty() {
return N == 0;
}
private class Node {
public Node(Item item) {
this.item = item;
}
Item item;
Node next;
}
}
public static void main(String[] args) {
LinkedListBasedGeneralQueue<Integer> q = new LinkedListBasedGeneralQueue<>();
q.insert(1);
q.insert(2);
q.insert(3);
StdOut.println(q.delete(1));
StdOut.println(q.delete(2));
StdOut.println(q.delete(1));
StdOut.println(q.isEmpty());
// 1
// 3
// 2
// true
}
}