Repository navigation
Expand file tree
/
Copy pathLinkedList.java
More file actions
141 lines (124 loc) · 3.08 KB
/
Copy pathLinkedList.java
File metadata and controls
141 lines (124 loc) · 3.08 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
137
138
139
140
141
package linkedlist;
public class LinkedList<T> {
private Node<T> head;
private int count;
public LinkedList() {
head = null;
count = 0;
}
public int getCount() {
return count;
}
public Node<T> getFirst() {
return head;
}
public Node<T> getLast() {
if(head == null) {
return null;
}
Node<T> current = head;
while(current.getNext() != null) {
current = current.getNext();
}
return current;
}
public Node<T> getAt(int index) {
if(index < 0 || index >= count) {
throw new IndexOutOfBoundsException();
}
Node<T> current = head;
for(int i = 0; i < index; i++) {
current = current.getNext();
}
return current;
}
public boolean search(T data) {
Node<T> current = head;
while(current != null) {
if(current.getData().equals(data)) {
return true;
}
current = current.getNext();
}
return false;
}
public void clear() {
head = null;
count = 0;
}
public void insertFirst(T data) {
var newNode = new Node<T>(data);
newNode.setNext(head);
head = newNode;
count++;
}
public void insertLast(T data) {
var lastNode = getLast();
var newNode = new Node<T>(data);
if(lastNode == null) {
head = newNode;
} else {
lastNode.setNext(newNode);
}
count++;
}
public void insertAt(T data, int index) {
if(index < 0 || index > count) {
throw new IndexOutOfBoundsException();
}
if(index == 0) {
insertFirst(data);
return;
}
if(index == count) {
insertLast(data);
return;
}
var current = head;
for(int i = 0; i < index - 1; i++) {
current = current.getNext();
}
var newNode = new Node<T>(data);
newNode.setNext(current.getNext());
current.setNext(newNode);
count++;
}
public void removeFirst() {
if(head == null) {
return;
}
head = head.getNext();
count--;
}
public void removeLast() {
if(head == null) {
return;
}
if(head.getNext() == null) {
head = null;
count--;
return;
}
var current = head;
while(current.getNext().getNext() != null) {
current = current.getNext();
}
current.setNext(null);
count--;
}
public void removeAt(int index) {
if(index < 0 || index >= count) {
throw new IndexOutOfBoundsException();
}
if(index == 0) {
removeFirst();
return;
}
var current = head;
for(int i = 0; i < index - 1; i++) {
current = current.getNext();
}
current.setNext(current.getNext().getNext());
count--;
}
}