-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyLinkedList.java
133 lines (120 loc) · 3.11 KB
/
MyLinkedList.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
public class MyLinkedList<E> {
private Node<E> head;
private int size;
public MyLinkedList() {
this.size = 0;
}
private static class Node<E> {
E value;
Node<E> next;
public Node(E value) {
this.value = value;
this.next = null;
}
}
public int size() {
return size;
}
public void append(E value) {
Node<E> newNode = new Node<E>(value);
if (head == null) {
head = newNode;
} else {
Node<E> node = head;
while (node.next != null) {
node = node.next;
}
node.next = newNode;
}
size++;
}
public void prepend(E value) {
Node<E> newNode = new Node<E>(value);
newNode.next = head;
head = newNode;
size++;
}
public E get(int index) {
checkForOutOfBounds(index);
Node<E> node = head;
for (int i = 0; i < index; i++) {
node = node.next;
}
return node.value;
}
public void insert(E value, int index) {
checkForOutOfBounds(index);
if (index == 0) {
this.prepend(value);
return;
} else if (index == size - 1) {
this.append(value);
return;
}
Node<E> newNode = new Node<E>(value);
Node<E> node = head;
for (int i = 1; i < index; i++) {
node = node.next;
}
newNode.next = node.next;
node.next = newNode;
size++;
}
public boolean remove(E value) {
if (head.value.equals(value)) {
head = head.next;
size--;
return true;
}
Node<E> prev = head;
Node<E> node = head.next;
while (node != null) {
if (node.value.equals(value)) {
prev.next = node.next;
size--;
return true;
}
prev = node;
node = node.next;
}
return false;
}
public E remove(int index) {
checkForOutOfBounds(index);
Node<E> prev = head;
Node<E> node = head.next;
if (index == 0) {
head = head.next;
size--;
return prev.value;
}
for (int i = 1; i < index; i++) {
prev = node;
node = node.next;
}
prev.next = node.next;
size--;
return node.value;
}
private void checkForOutOfBounds(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
}
public String toString() {
if (size == 0)
return "[ ]";
Node<E> node = head;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("[ ");
sb.append(node.value);
sb.append(" ]");
if (node.next != null) {
node = node.next;
sb.append(" --> ");
}
}
return sb.toString();
}
}