-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimpleLinkedList.java
More file actions
136 lines (118 loc) · 3.22 KB
/
Copy pathSimpleLinkedList.java
File metadata and controls
136 lines (118 loc) · 3.22 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
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
package list;
import list.SimpleList;
import java.util.Iterator;
public class SimpleLinkedList<V> implements SimpleList<V>, Iterable<V> {
int size = 0;
Node<V> first = null;
Node<V> last = null;
public int size(){
return size;
}
@Override
public boolean add(V value) {
if (size == 0) {
first = new Node(first, last, value);
last = first;
size++;
return true;
}
if (size > 0) {
Node newNode = new Node(last, null, value);
last.setBehind(newNode);
last = newNode;
size++;
return true;
}
return false;
}
@Override
public V get(int index) {
Node<V> target = first;
if (index == 0) {
return target.getValue();
}
if(index == size-1){
return last.getValue();
}
if (index > 0 && index < size) {
for (int i = 0; i < index; i++) {
target = target.getBehind();
}
return target.getValue();
}
throw new IndexOutOfBoundsException();
}
@Override
public boolean delete(int index) {
Node target = first;
if(index == 0){
Node node = first.getBehind();
node.setAhead(null);
first = node;
size--;
return true;
}
if (index == size-1) {
Node node = last.getAhead();
node.setBehind(null);
last = node;
size--;
return true;
}
if (index > 0 && index < size) {
for (int i = 0; i < index; i++) {
target = target.getBehind();
}
Node node = target.getAhead();
node.setBehind(target.getBehind());
node = target.getBehind();
node.setAhead(target.getAhead());
size--;
return true;
}
throw new IndexOutOfBoundsException();
}
@Override
public Iterator<V> iterator() {
return new Iterator<V>() {
Node<V> cursor = first;
@Override
public boolean hasNext() {
return cursor != null;
}
@Override
public V next() {
V value = cursor.getValue();
if (hasNext()) {
cursor = cursor.getBehind();
}
return value;
}
};
}
private class Node<V> {
V value;
Node ahead;
Node behind;
Node(Node ahead, Node behind, V value) {
this.ahead = ahead;
this.behind = behind;
this.value = value;
}
private void setBehind(Node newNode) {
this.behind = newNode;
}
private void setAhead(Node newNode) {
this.ahead = newNode;
}
private Node getAhead() {
return ahead;
}
private Node getBehind() {
return behind;
}
private V getValue() {
return value;
}
}
}