-
Notifications
You must be signed in to change notification settings - Fork 0
/
CycleList.java
90 lines (72 loc) · 2.19 KB
/
CycleList.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
import java.util.*;
public class CycleList<T> {
private T data;
private CycleList<T> next;
public CycleList(T data) {
this.data = data;
this.next = this;
}
public CycleList(T[] data) {
CycleList<T> current = this;
Iterator<T> it = Arrays.asList(data).iterator();
current.data = it.next();
while (it.hasNext()) {
current.next = new CycleList<>(it.next());
current = current.next;
}
current.next = this;
}
public T getData() {
return this.data;
}
public CycleList<T> getNext() {
return this.next;
}
public void add(T data) {
CycleList<T> another = new CycleList<>(data);
if (this.getNext() == null) {
this.next = another;
another.next = this;
} else {
CycleList<T> save = this.getNext();
this.next = another;
another.next = save;
}
}
public void fill(List<T> list) {
for (T element : list) {
this.add(element);
}
}
public Deque<T> toDeque() {
Deque<T> stack = new LinkedList<>();
CycleList<T> current = this.getNext();
T save = this.getData();
while (!save.equals(current.getData())) {
stack.push(current.getData());
current = current.getNext();
}
return stack;
}
public CycleList<T> copy() {
CycleList<T> another = new CycleList<>(this.getData());
Deque<T> stack = this.toDeque();
while (!stack.isEmpty()) {
another.add(stack.poll());
}
return another;
}
@Override
public String toString() {
CycleList<T> current = this.getNext();
T save = this.getData();
StringBuilder str = new StringBuilder("__ -- " + save.toString());
while (current != null && !save.equals(current.getData())) {
str.append(" -- ");
str.append(current.getData());
current = current.getNext();
}
str.append("__");
return str.toString();
}
}