0%

『LeetCode』707 设计链表

题目

707. 设计链表

设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:valnextval 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

在链表类中实现这些功能:

  • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1
  • addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
  • addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
  • addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
  • deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。

示例:

MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2); //链表变为1-> 2-> 3
linkedList.get(1); //返回2
linkedList.deleteAtIndex(1); //现在链表是1-> 3
linkedList.get(1); //返回3

提示:

  • 所有val值都在 [1, 1000] 之内。
  • 操作次数将在 [1, 1000] 之内。
  • 请不要使用内置的 LinkedList 库。

标签

设计, 链表


题解

【设计链表】基本数据结构

双向链表

手动构建基本的双向链表即可,注意对 index 的越界处理。

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
# Code language: Python
class Node:
def __init__(self, val=0, next=None, prev=None):
self.val, self.next, self.prev = val, next, prev

def add_next(self, val):
cur = Node(val, self.next, self)
self.next.prev = cur
self.next = cur

def add_prev(self, val):
cur = Node(val, self, self.prev)
self.prev.next = cur
self.prev = cur

@staticmethod
def get_iter(node):
p = node
while p != node:
yield p
p = p.next

def __iter__(self):
return Node.get_iter(self)

class MyLinkedList(object):

def __init__(self):
self.head = Node()
self.head.next, self.head.prev = self.head, self.head
self.size = 0

def get(self, index: int) -> int:
if index >= self.size or index < 0:
return -1
p = self.head.next
for _ in range(index):
p = p.next
return p.val

def addAtHead(self, val: int) -> None:
self.head.add_next(val)
self.size += 1

def addAtTail(self, val: int) -> None:
self.head.add_prev(val)
self.size += 1

def addAtIndex(self, index: int, val: int) -> None:
if index > self.size: return
p = self.head
for _ in range(index):
p = p.next
p.add_next(val)
self.size += 1

def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
p = self.head
for _ in range(index):
p = p.next
cur = p.next
cur.next.prev = p
p.next = cur.next
self.size -= 1

def show(self):
print("LinkList")
for p in self.head:
print(f" -> {p.val}", end='')
print()
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
// Code language: Java
class Node {
public int val;
public Node next, prev;
public Node(int _val, Node _next, Node _prev) {
val = _val; next = _next; prev = _prev;
}
public Node(int _val) {
val = _val; next = null; prev = null;
}
}

class MyLinkedList {
private Node head;
private int size;

public MyLinkedList() {
head = new Node(0);
head.next = head; head.prev = head;
size = 0;
}

public int get(int index) {
if (index >= size || index < 0) return -1;
Node p = head.next;
for (; index > 0; --index) p = p.next;
return p.val;
}

public void addAtHead(int val) {
Node cur = new Node(val, head.next, head);
head.next.prev = cur;
head.next = cur;
++size;
}

public void addAtTail(int val) {
Node cur = new Node(val, head, head.prev);
head.prev.next = cur;
head.prev = cur;
++size;
}

public void addAtIndex(int index, int val) {
if (index > size) return;
Node p = head;
for (; index > 0; --index) p = p.next;
Node cur = new Node(val, p.next, p);
p.next.prev = cur;
p.next = cur;
++size;
}

public void deleteAtIndex(int index) {
if (index < 0 || index >= size) return;
Node p = head;
for (; index > 0; --index) p = p.next;
Node cur = p.next;
cur.next.prev = p;
p.next = cur.next;
--size;
}

private void printall() {
Node p = head.next;
System.out.printf("Head ");
for (int i = 0; i < size; ++i) {
System.out.printf(". %d", p.val);
p = p.next;
}
if (p != head) System.out.printf(". Cycle(%d)!", p.val);
System.out.printf("\n");
}
}
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
// Code language: C++
struct Node{
int val;
Node *next, *prev;
Node(int _val, Node *_next, Node *_prev):val(_val), next(_next), prev(_prev){}
Node(int _val):val(_val), next(nullptr), prev(nullptr){}
};

class MyLinkedList {
public:
Node* head;
int size;
MyLinkedList() {
head = new Node(0);
head->next = head; head->prev = head;
size = 0;
}

int get(int index) {
if (index >= size || index < 0) return -1;
auto p = head->next;
for (; index > 0; --index) p = p->next;
return p->val;
}

void addAtHead(int val) {
Node *cur = new Node(val, head->next, head);
head->next->prev = cur;
head->next = cur;
++size;
}

void addAtTail(int val) {
Node *cur = new Node(val, head, head->prev);
head->prev->next = cur;
head->prev = cur;
++size;
}

void addAtIndex(int index, int val) {
if (index > size) return;
Node* p = head;
for (; index > 0; --index) p = p->next;
Node *cur = new Node(val, p->next, p);
p->next->prev = cur;
p->next = cur;
++size;
}

void deleteAtIndex(int index) {
if (index < 0 || index >= size) return;
Node* p = head;
for (; index > 0; --index) p = p->next;
Node *cur = p->next;
cur->next->prev = p;
p->next = cur->next;
delete cur;
--size;
}

~MyLinkedList() {
for (Node *p = head->next, *q; p != head;) {
q = p->next;
delete p;
p = q;
}
delete head;
}

void printall() {
Node* p = head->next;
printf("Head ");
for (int i = 0; i < size; ++i) {
printf("-> %d", p->val);
p = p->next;
}
if (p != head) printf("-> Cycle(%d)!", p->val);
putchar('\n');
}
};
  • 时间复杂度: 涉及 index 的均为 \(O(n)\), 否则为 \(O(1)\)
  • 空间复杂度: 均为 \(O(1)\)

单链表

也可以用单链表,但处理起来比较麻烦,这里建议维护一个尾指针

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
# Code language: Python
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class MyLinkedList:

def __init__(self):
"""
Initialize your data structure here.
"""
self.dummy = Node()
self.tail = self.dummy
self.size = 0

def get(self, index: int) -> int:
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
"""
if 0 <= index < self.size:
if index == self.size - 1:
return self.tail.val
p = self.dummy.next
while index:
p = p.next
index -= 1
return p.val
else:
return -1

def addAtHead(self, val: int) -> None:
"""
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.
"""
self.dummy.next = Node(val, self.dummy.next)
if self.size == 0:
self.tail = self.dummy.next
self.size += 1

def addAtTail(self, val: int) -> None:
"""
Append a node of value val to the last element of the linked list.
"""
self.tail.next = Node(val, self.tail.next)
self.tail = self.tail.next
self.size += 1

def addAtIndex(self, index: int, val: int) -> None:
"""
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.
"""
if index < 0:
self.addAtHead(val)
elif index == self.size:
self.addAtTail(val)
elif index > self.size:
pass
else:
p = self.dummy
while index:
p = p.next
index -= 1
p.next = Node(val, p.next)
self.size += 1

def deleteAtIndex(self, index: int) -> None:
"""
Delete the index-th node in the linked list, if the index is valid.
"""
if 0 <= index < self.size:
p = self.dummy
while index:
p = p.next
index -= 1
if p.next == self.tail:
self.tail = p
p.next = p.next.next
self.size -= 1
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
87
// Code language: C++
struct MyListNode {
int val;
MyListNode* next;
MyListNode(): val(0), next(nullptr) {}
MyListNode(int v): val(v), next(nullptr) {}
MyListNode(int v, MyListNode* n): val(v), next(n) {}
};

class MyLinkedList {
public:
/** Initialize your data structure here. */
MyLinkedList() {
dummy = new MyListNode;
tail = dummy;
size = 0;
}

/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
/* 非法输入 */
if (index < 0 || index >= size)
return -1;
/* 最后一个结点可以由tail指针获得,无需遍历了 */
else if (index == size - 1)
return tail->val;
MyListNode* p = dummy->next;
while (index-- > 0)
p = p->next;
return p->val;
}

/** 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. */
void addAtHead(int val) {
dummy->next = new MyListNode(val, dummy->next);
/* 如果是向空链表插入元素,要移动tail指针 */
if (++size == 1) tail = dummy->next;
}

/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
tail->next = new MyListNode(val, tail->next);
tail = tail->next;
++size;
}

/** 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. */
void addAtIndex(int index, int val) {
if (index <= 0)
addAtHead(val);
else if (index == size)
addAtTail(val);
else if (index < size) {
MyListNode* p = dummy;
while (index-- > 0) p = p->next;
p->next = new MyListNode(val, p->next);
++size;
}
}

/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if (index >= 0 && index < size) {
/* 查找待删除结点的前驱结点 */
MyListNode* p = dummy;
while (index-- > 0) p = p->next;
/* 如果删除的是tail结点,需要移动tail指针 */
if (p->next == tail) tail = p;
MyListNode* q = p->next;
p->next = p->next->next;
--size;
delete q;
}
}

~MyLinkedList() {
while (dummy != nullptr) {
tail = dummy;
dummy = dummy->next;
delete tail;
}
}

private:
MyListNode *dummy, *tail;
int size;
};
  • 时间复杂度: 涉及 index 均为 \(O(n)\), 否则为 \(O(1)\)
  • 空间复杂度: 均为 \(O(1)\)

如果对你有帮助的话,请给我点个赞吧~

欢迎前往 我的博客Algorithm - Github 查看更多题解

--- ♥ end ♥ ---

欢迎关注我呀~