You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
30
+
publicintget(intindex) {
31
+
if (index < 0 || index >= count) {
32
+
return -1;
33
+
}
34
+
ListNodecur = dummyHead;
35
+
while (index-- >= 0) {
36
+
cur = cur.next;
37
+
}
38
+
returncur.val;
39
+
}
40
+
41
+
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
42
+
publicvoidaddAtHead(intval) {
43
+
ListNodenewNode = newListNode(val);
44
+
newNode.next = dummyHead.next;
45
+
dummyHead.next = newNode;
46
+
count++;
47
+
}
48
+
49
+
/** Append a node of value val to the last element of the linked list. */
50
+
publicvoidaddAtTail(intval) {
51
+
ListNodecur = dummyHead;
52
+
while (cur.next != null) {
53
+
cur = cur.next;
54
+
}
55
+
cur.next = newListNode(val);
56
+
count++;
57
+
}
58
+
59
+
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
60
+
publicvoidaddAtIndex(intindex, intval) {
61
+
if (index == count) {
62
+
addAtTail(val);
63
+
} elseif (index < count) {
64
+
ListNodecur = dummyHead;
65
+
while (index-- > 0) {
66
+
cur = cur.next;
67
+
}
68
+
ListNodenewNode = newListNode(val);
69
+
newNode.next = cur.next;
70
+
cur.next = newNode;
71
+
count++;
72
+
}
73
+
}
74
+
75
+
/** Delete the index-th node in the linked list, if the index is valid. */
0 commit comments