-
Notifications
You must be signed in to change notification settings - Fork 8
/
SinglyLinkedList.java
53 lines (47 loc) · 1.3 KB
/
SinglyLinkedList.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
public class SinglyLinkedList<T> {
private LLNode head = null;
private LLNode tail = null;
private int size = 0;
private static class LLNode <T> {
LLNode next;
T data;
LLNode(T data) {
this.data = data;
next = null;
}
}
public boolean isEmpty() { return head == null; }
public int size() { return size; }
public T getHeadData() { return (T) head.data; }
public T getTailData() { return (T) tail.data; }
public void addLast(T data) {
LLNode newest = new LLNode(data);
if(isEmpty()) head = tail = newest;
else {
tail.next = newest;
tail = newest;
}
size++;
}
public T removeLast() {
if(isEmpty())
throw new RuntimeException("ERROR: List empty");
T tail_data = (T) tail.data;
LLNode tail_prev = head;
while(tail_prev.next != tail) {
tail_prev = tail_prev.next;
}
tail_prev.next = null;
tail = tail_prev;
--size;
return tail_data;
}
public T removeFirst() {
if (isEmpty())
throw new RuntimeException("ERROR: List empty");
T head_data = (T) head.data;
--size;
head = head.next;
return head_data;
}
}