-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList_hellomatia.java
More file actions
102 lines (85 loc) · 2.12 KB
/
Copy pathLinkedList_hellomatia.java
File metadata and controls
102 lines (85 loc) · 2.12 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
package List.LinkedList;
import List.List;
public class LinkedList_hellomatia<E> implements List<E> {
private final Node head;
private Node tail;
private int size;
public LinkedList_hellomatia() {
this.head = new Node(null);
this.tail = head;
}
@Override
public void insert(E data) {
tail.setNext(createNode(data));
tail = tail.getNext();
size++;
}
private Node createNode(E data) {
return new Node(data);
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean contains(E o) {
for (Node now = head.getNext(); now != null; now = now.getNext()) {
if (now.getData().equals(o)) {
return true;
}
}
return false;
}
@Override
public E get(int index) {
checkIndex(index);
return getNode(index).getData();
}
@Override
public E remove(int index) {
checkIndex(index);
Node removeNode = getNode(index);
Node prevNode = getNode(index - 1);
if (removeNode == tail) {
prevNode.setNext(null);
tail = prevNode;
} else {
prevNode.setNext(removeNode.getNext());
}
removeNode.setNext(null);
size--;
return removeNode.getData();
}
private void checkIndex(int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException();
}
}
private Node getNode(int index) {
Node now = head.getNext();
for (int i = 0; i < index; i++) {
now = now.getNext();
}
return now;
}
private class Node {
private final E data;
private Node next;
protected Node(E data) {
this.data = data;
}
private Node getNext() {
return next;
}
private void setNext(Node next) {
this.next = next;
}
private E getData() {
return data;
}
}
}