Skip to content

Commit bab2284

Browse files
authored
Merge pull request #2320 from lokeshmvs21/main
create: 0707-design-linked-list.java
2 parents 4aa5a6b + b3c86cf commit bab2284

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

java/0707-design-linked-list.java

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
class ListNode {
2+
int val;
3+
ListNode prev;
4+
ListNode next;
5+
public ListNode(int val) {
6+
this.val = val;
7+
this.prev = null;
8+
this.next = null;
9+
}
10+
}
11+
12+
class MyLinkedList {
13+
14+
ListNode left;
15+
ListNode right;
16+
17+
public MyLinkedList() {
18+
left = new ListNode(0);
19+
right = new ListNode(0);
20+
left.next = right;
21+
right.prev = left;
22+
}
23+
24+
public int get(int index) {
25+
ListNode cur = left.next;
26+
while(cur != null && index > 0) {
27+
cur = cur.next;
28+
index -= 1;
29+
}
30+
if(cur != null && cur != right && index == 0) {
31+
return cur.val;
32+
}
33+
return -1;
34+
}
35+
36+
public void addAtHead(int val) {
37+
ListNode node = new ListNode(val);
38+
ListNode next = left.next;
39+
ListNode prev = left;
40+
prev.next = node;
41+
next.prev = node;
42+
node.next = next;
43+
node.prev = prev;
44+
}
45+
46+
public void addAtTail(int val) {
47+
ListNode node = new ListNode(val);
48+
ListNode next = right;
49+
ListNode prev = right.prev;
50+
prev.next = node;
51+
next.prev = node;
52+
node.next = next;
53+
node.prev = prev;
54+
}
55+
56+
public void addAtIndex(int index, int val) {
57+
ListNode cur = left.next;
58+
while(cur != null && index > 0) {
59+
cur = cur.next;
60+
index -= 1;
61+
}
62+
if(cur != null && index == 0) {
63+
ListNode node = new ListNode(val);
64+
ListNode next = cur;
65+
ListNode prev = cur.prev;
66+
prev.next = node;
67+
next.prev = node;
68+
node.next = next;
69+
node.prev = prev;
70+
}
71+
}
72+
73+
public void deleteAtIndex(int index) {
74+
ListNode cur = left.next;
75+
while(cur != null && index > 0) {
76+
cur = cur.next;
77+
index -= 1;
78+
}
79+
if(cur != null && cur != right && index == 0) {
80+
ListNode next = cur.next;
81+
ListNode prev = cur.prev;
82+
next.prev = prev;
83+
prev.next = next;
84+
}
85+
}
86+
}

0 commit comments

Comments
 (0)