Skip to content

Commit 5bb50f4

Browse files
committed
设计链表
1 parent d1037be commit 5bb50f4

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package question0707_design_linked_list;
2+
3+
/**
4+
* 增加虚拟头节点方便操作。
5+
*
6+
* 执行用时:70ms,击败97.07%。消耗内存:45MB,击败86.60%。
7+
*/
8+
public class MyLinkedList {
9+
private class ListNode {
10+
int val;
11+
12+
ListNode next;
13+
14+
ListNode(int val) {
15+
this.val = val;
16+
}
17+
}
18+
19+
private ListNode dummyHead;
20+
21+
private int count;
22+
23+
/** Initialize your data structure here. */
24+
public MyLinkedList() {
25+
dummyHead = new ListNode(-1);
26+
count = 0;
27+
}
28+
29+
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
30+
public int get(int index) {
31+
if (index < 0 || index >= count) {
32+
return -1;
33+
}
34+
ListNode cur = dummyHead;
35+
while (index-- >= 0) {
36+
cur = cur.next;
37+
}
38+
return cur.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+
public void addAtHead(int val) {
43+
ListNode newNode = new ListNode(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+
public void addAtTail(int val) {
51+
ListNode cur = dummyHead;
52+
while (cur.next != null) {
53+
cur = cur.next;
54+
}
55+
cur.next = new ListNode(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+
public void addAtIndex(int index, int val) {
61+
if (index == count) {
62+
addAtTail(val);
63+
} else if (index < count) {
64+
ListNode cur = dummyHead;
65+
while (index-- > 0) {
66+
cur = cur.next;
67+
}
68+
ListNode newNode = new ListNode(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. */
76+
public void deleteAtIndex(int index) {
77+
if (index < 0 || index >= count) {
78+
return;
79+
}
80+
ListNode cur = dummyHead;
81+
while (index-- > 0) {
82+
cur = cur.next;
83+
}
84+
cur.next = cur.next.next;
85+
count--;
86+
}
87+
}

0 commit comments

Comments
 (0)