876. Middle of the Linked List
Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
Constraints:
- The number of nodes in the list is in the range
[1, 100]
. 1 <= Node.val <= 100
SOL:
參考李根逸博士的影片,使用 快慢指針 的方法來解決。
【C 語言的 LeetCode 30 天挑戰】第八天 (Middle of the Linked List)
需要注意的是,->next前面的東西不能為空,否則編譯會有問題。
原本這三者都應該要確認非空:
fast!=NULL && fast->next!=NULL && slow!=NULL
但因為 fast 一定走的比 slow 還快,所以只要 fast 非空,則 slow 也非空,故 slow!=NULL 可以拿掉。
python 解法參考:[LeetCode] 876. Middle of the Linked List
文章標籤
全站熱搜