forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0707-design-linked-list.java
86 lines (78 loc) · 2.05 KB
/
0707-design-linked-list.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
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
class ListNode {
int val;
ListNode prev;
ListNode next;
public ListNode(int val) {
this.val = val;
this.prev = null;
this.next = null;
}
}
class MyLinkedList {
ListNode left;
ListNode right;
public MyLinkedList() {
left = new ListNode(0);
right = new ListNode(0);
left.next = right;
right.prev = left;
}
public int get(int index) {
ListNode cur = left.next;
while(cur != null && index > 0) {
cur = cur.next;
index -= 1;
}
if(cur != null && cur != right && index == 0) {
return cur.val;
}
return -1;
}
public void addAtHead(int val) {
ListNode node = new ListNode(val);
ListNode next = left.next;
ListNode prev = left;
prev.next = node;
next.prev = node;
node.next = next;
node.prev = prev;
}
public void addAtTail(int val) {
ListNode node = new ListNode(val);
ListNode next = right;
ListNode prev = right.prev;
prev.next = node;
next.prev = node;
node.next = next;
node.prev = prev;
}
public void addAtIndex(int index, int val) {
ListNode cur = left.next;
while(cur != null && index > 0) {
cur = cur.next;
index -= 1;
}
if(cur != null && index == 0) {
ListNode node = new ListNode(val);
ListNode next = cur;
ListNode prev = cur.prev;
prev.next = node;
next.prev = node;
node.next = next;
node.prev = prev;
}
}
public void deleteAtIndex(int index) {
ListNode cur = left.next;
while(cur != null && index > 0) {
cur = cur.next;
index -= 1;
}
if(cur != null && cur != right && index == 0) {
ListNode next = cur.next;
ListNode prev = cur.prev;
next.prev = prev;
prev.next = next;
}
}
}