Design Linked List LeetCode solution in Java

1
class MyLinkedList {
2

3
public class ListNode {
4
public int val;
5
public ListNode next;
6

7
public ListNode() {}
8

9
public ListNode(int val) {
10
this.val = val;
11
}
12

13
public ListNode(int val, ListNode next) {
14
this.val = val;
15
this.next = next;
16
}
17
}
18

19
private ListNode head;
20
private ListNode tail;
21
private int length;
22

23
public MyLinkedList() {
24
length = 0;
25
}
26

27
public int get(int index) {
28
if (index > length - 1 || index < 0) return -1;
29
int thisIndex = 0;
30
ListNode temp = head;
31
while (thisIndex != index) {
32
temp = temp.next;
33
thisIndex++;
34
}
35
return temp.val;
36
}
37

38
public void addAtHead(int val) {
39
head = new ListNode(val, head);
40
length++;
41
if (length == 1) tail = head;
42
}
43

44
public void addAtTail(int val) {
45
length++;
46
if (length == 1) {
47
ListNode onlyNode = new ListNode(val);
48
head = onlyNode;
49
tail = head;
50
return;
51
}
52
tail.next = new ListNode(val);
53
tail = tail.next;
54
}
55

56
public void addAtIndex(int index, int val) {
57
if (index <= length) {
58
if (index == 0) {
59
addAtHead(val);
60
return;
61
}
62
if (index == length) {
63
addAtTail(val);
64
return;
65
}
66
length++;
67
ListNode temp = head;
68
int thisIndex = 0;
69
while (thisIndex != index - 1) {
70
temp = temp.next;
71
thisIndex++;
72
}
73
temp.next = new ListNode(val, temp.next);
74
}
75
}
76

77
public void deleteAtIndex(int index) {
78
if (index >= length || index < 0) return;
79
length--;
80
if (index == 0) {
81
head = head.next;
82
return;
83
}
84
ListNode temp = head;
85
int thisIndex = 0;
86
while (thisIndex != index - 1) {
87
temp = temp.next;
88
thisIndex++;
89
}
90
if (index == length) {
91
tail = temp;
92
temp.next = null;
93
} else temp.next = temp.next.next;
94
}
95
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0