-
Notifications
You must be signed in to change notification settings - Fork 28
/
Children.java
105 lines (82 loc) · 1.97 KB
/
Children.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
package ds_010_trees;
public class Children<T> {
private LinkNode<T> START_SENTINEL = new LinkNode<>(null);
private LinkNode<T> END_SENTINEL = new LinkNode<>(null);
private int size = 0;
public Children() {
START_SENTINEL.next = END_SENTINEL;
END_SENTINEL.prev = START_SENTINEL;
}
public void add(T data) {
LinkNode<T> newNode = new LinkNode<>(data);
newNode.prev = END_SENTINEL.prev;
newNode.next = END_SENTINEL;
END_SENTINEL.prev.next = newNode;
END_SENTINEL.prev = newNode;
size++;
}
public T remove(T data) {
LinkNode<T> removed = findNode(data);
if(removed == null) {
return null;
} else {
removed.next.prev = removed.prev;
removed.prev.next = removed.next;
size --;
return removed.data;
}
}
public LinkNode<T> findNode(T data) {
for(LinkNode<T> curr = START_SENTINEL.next; curr != END_SENTINEL; curr = curr.next) {
if(curr.data.equals(data)) {
return curr;
}
}
return null;
}
public T find(T data) {
for(LinkNode<T> curr = START_SENTINEL.next; curr != END_SENTINEL; curr = curr.next) {
if(curr.data.equals(data)) {
return curr.data;
}
}
return null;
}
public LinkNode<T> findByIndex(int index) {
LinkNode<T> curr = START_SENTINEL.next;
for(int i = 0; curr != END_SENTINEL; curr = curr.next, i++) {
if(i == index) {
return curr;
}
}
return null;
}
// trivial
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void printChildren() {
System.out.print("Children: ");
if(isEmpty()) {
System.out.print("No children!");
} else {
for(LinkNode<T> curr = START_SENTINEL.next; curr != END_SENTINEL; curr = curr.next) {
System.out.printf("%s ", curr.data);
}
}
System.out.print("\n");
}
static class LinkNode<T> {
private T data;
private LinkNode<T> prev;
private LinkNode<T> next;
public LinkNode(T data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
}