Catalogue
- 1. Introduction
- 2. Basic Function
- 3. 203. Remove Linked List Elements
- 4. 19. Remove Nth Node From End of List
- 5. 237. Delete Node in a Linked List
- 6. 83. Remove Duplicates from Sorted List
- 7. 82. Remove Duplicates from Sorted List II
- 8. 21. Merge Two Sorted Lists
- 9. 23. Merge k Sorted Lists
- 10. 138. Copy List with Random Pointer
- 11. 430. Flatten a Multilevel Doubly Linked List
Introduction
Prerequisite
- Linear Structure : Array:Phisical, Linked List:是由Pointer连起来的,不一定是物理连续的!
- 链表的题目往往算不上“算法性”题,只是一种模拟操作的题
- 考察的重点在于bug free,是否对写代码有熟练度!
Key Point
- 1 When you want to de-reference a List Node, make sure it is not a NULL Pointer.
- No matter when you use “.”, 一定要注意判断前面的Reference是否为空!!!
- 2 Never ever lost the control of the head pointer of the Linked List.
- 经常需要缓存nxt指针或者prev指针,都是因为当你改变链表结构的时候很容易丢失之前或者之后的信息!
Tips
DummyNode, Why or When should we use a dummy Node?
- When we want to append new elements to an initially empty linkedlist, we do not have an initial head node. In this case, we can new a dummy node to act as a head node.
- 链表的结构发生变化
Two or More Pointers
- We usually use many pointer to manipulate the node of the linked list
Basic Function
Find the middle node of a linked List
- Odd, Even
1
2
3
4
5
6
7def findMiddleNode(head):
if not head: return head
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
return fast
Insert a node in a sorted linked list
203. Remove Linked List Elements
- Two pointers : prev, cur
1 | class Solution(object): |
19. Remove Nth Node From End of List
- 快慢指针维护一个长度为n的滑动窗口
1 | class Solution(object): |
237. Delete Node in a Linked List
- 很奇怪的一道题,做法也很奇怪
- 往往删除单链表的一个节点,需要有头节点或者前一个节点来绕过删除的节点,这道题只给了要删除的节点(单链表拿不到previous的节点),只能通过节点覆盖来做。
1 | class Solution(object): |
83. Remove Duplicates from Sorted List
- 和Remove Duplicate from Array一毛一样同样是同向双指针
1 | class Solution(object): |
82. Remove Duplicates from Sorted List II
- 删除所有的duplicate,只保留distinct的元素!
- 1 找到重复的元素
- 2 用while循环删除掉所有
1 | class Solution(object): |
21. Merge Two Sorted Lists
- DummyNode的使用
1 | class Solution(object): |
23. Merge k Sorted Lists
- heap
1 | # Time : O(nlogk), Space : (k) |
138. Copy List with Random Pointer
- Hash Table
= NewNode
1 | class Solution(object): |
1 | # Recursion |
430. Flatten a Multilevel Doubly Linked List
1 | class Solution(object): |