Linked-List
定義:
node跟node所組成的結構,每個node都會有數值(value)跟指向下一node的連結(next)
Data Structure and Algorithms — Linked List
- Simple Linked List:
單一方向 Linked List,包含目前節點的值、下個節點的連結
EX:12->99>37->null - Doubly Linked List:
雙方向 Linked List,包含目前節點的值、上下一個節點的連結
EX:null<->12<->99<->37->null - Circular Linked List:
環狀Linked List,最後一個node的next會是第一個node
EX:12->99->-37->12->...
實作:
function 定義
ES6 語法
Linked-List 的運算方法
- 建立
- 查詢(遍歷)
- 新增
- 移除
- 插入
Linked-List 跟 Array 差別:
From Lisked-List to Tree:
- Tree 就是非線性的 Linked-List,每個節點都會有兩個往下的選擇,一個往左延伸、另一個往右延伸
- 實作時只需要追加一個節點,這就是 Linked-List 和 Tree 的最大差別
參考資料:
練習題:
206. Reverse Linked List (E)
題目說明:
Given the head
of a singly linked list, reverse the list, and return the reversed list.
給一個link list的head,回傳順序顛倒的link list
條件:
- The number of nodes in the list is the range
[0, 5000]
. -5000 <= Node.val <= 5000
優化:
A linked list can be reversed either iteratively or recursively. Could you implement both?
解法:
Iterative / Swapping
Recursion
Stack
參考:
製作link-List:
83. Remove Duplicates from Sorted List
題目說明:
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
條件:
- The number of nodes in the list is in the range
[0, 300]
. -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
解法:
142. Linked List Cycle II
題目說明:
Given the head
of a linked list, return the node where the cycle begins. If there is no cycle, return null
.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next
pointer. Internally, pos
is used to denote the index of the node that tail's next
pointer is connected to (0-indexed). It is -1
if there is no cycle. Note that pos
is not passed as a parameter.
條件:
- The number of the nodes in the list is in the range
[0, 104]
. -105 <= Node.val <= 105
pos
is-1
or a valid index in the linked-list.
優化:
Can you solve it using O(1)
(i.e. constant) memory?
解法:
725. Split Linked List in Parts
題目說明:
Given the head
of a singly linked list and an integer k
, split the linked list into k
consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return an array of the k
parts.
條件:
- The number of nodes in the list is in the range
[0, 1000]
. 0 <= Node.val <= 1000
1 <= k <= 50