-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSinglyList.java
More file actions
120 lines (100 loc) · 2.43 KB
/
SinglyList.java
File metadata and controls
120 lines (100 loc) · 2.43 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
public class SinglyList<T> {
private static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
this.next = null;
}
}
private Node<T> head;
private Node<T> tail;
private int size;
public SinglyList() {
head = null;
tail = null;
size = 0;
}
public void addFirst(T x) {
Node<T> n = new Node<>(x);
n.next = head;
head = n;
if (tail == null) {
tail = head;
}
size++;
}
public void addLast(T x) {
Node<T> n = new Node<>(x);
if (head == null) {
head = n;
tail = n;
} else {
tail.next = n;
tail = n;
}
size++;
}
public T removeFirst() {
if (head == null) return null;
T removed = head.data;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return removed;
}
public boolean remove(T x) {
Node<T> prev = null;
Node<T> cur = head;
while (cur != null) {
if ((x == null && cur.data == null) || (x != null && x.equals(cur.data))) {
if (prev == null) {
head = cur.next;
} else {
prev.next = cur.next;
}
if (cur == tail) {
tail = prev;
}
size--;
if (size == 0) {
head = null;
tail = null;
}
return true;
}
prev = cur;
cur = cur.next;
}
return false;
}
public int size() {
return size;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node<T> cur = head;
while (cur != null) {
sb.append(cur.data).append(" -> ");
cur = cur.next;
}
sb.append("null");
return sb.toString();
}
public String toValueString() {
StringBuilder sb = new StringBuilder();
Node<T> cur = head;
while (cur != null) {
sb.append(cur.data);
if (cur.next != null) sb.append(" ");
cur = cur.next;
}
return sb.toString();
}
public boolean isEmpty() {
return size == 0;
}
}