Skip to content

Commit 2e03ce9

Browse files
committed
Time: 9 ms (61.28%), Space: 45.7 MB (51.63%) - LeetHub
1 parent 769b57b commit 2e03ce9

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
class MyLinkedList {
2+
3+
public static class Node {
4+
int value;
5+
Node next;
6+
public Node(int v) {
7+
value = v;
8+
}
9+
}
10+
11+
private final Node head;
12+
private int size;
13+
14+
public MyLinkedList() {
15+
head = new Node(0);
16+
size = 0;
17+
}
18+
19+
public int get(int index) {
20+
if(index < 0 || index >= size) {
21+
return -1;
22+
}
23+
Node cur = head.next;
24+
for(int i = 0; i < index; i++) {
25+
cur = cur.next;
26+
}
27+
return cur.value;
28+
29+
}
30+
31+
public void addAtHead(int val) {
32+
addAtIndex(0, val);
33+
}
34+
35+
public void addAtTail(int val) {
36+
addAtIndex(size, val);
37+
}
38+
39+
public void addAtIndex(int index, int val) {
40+
if(index < 0|| index > size) {
41+
return ;
42+
}
43+
Node prev = head;
44+
for(int i = 0; i < index; i++) {
45+
prev = prev.next;
46+
}
47+
Node n = new Node(val);
48+
n.next = prev.next;
49+
prev.next = n;
50+
size++;
51+
52+
}
53+
54+
public void deleteAtIndex(int index) {
55+
if(index < 0|| index >= size) {
56+
return ;
57+
}
58+
Node prev = head;
59+
for(int i = 0; i < index; i++) {
60+
prev = prev.next;
61+
}
62+
prev.next = prev.next.next;
63+
size--;
64+
65+
}
66+
}
67+
68+
/**
69+
* Your MyLinkedList object will be instantiated and called as such:
70+
* MyLinkedList obj = new MyLinkedList();
71+
* int param_1 = obj.get(index);
72+
* obj.addAtHead(val);
73+
* obj.addAtTail(val);
74+
* obj.addAtIndex(index,val);
75+
* obj.deleteAtIndex(index);
76+
*/

0 commit comments

Comments
 (0)