1. 程式人生 > >leetcode876. Middle of the Linked List(尋找連結串列的中間元素)

leetcode876. Middle of the Linked List(尋找連結串列的中間元素)

題目要求 (高頻題)

給一個帶有頭節點head並且非空的單鏈表。返回連結串列的中間節點。
如果有兩個中間結點,那麼返回第二個。

示例

// Example 1
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3.  (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. //Example 2 Input: [1,2,3,4,5,6] Output: Node 4 from this list (Serialization: [4,5,6]) Since the list has two middle nodes with values 3 and 4, we return the second one. Note: the number of nodes in the given list will be between 1
and 100.

解體思路

快慢指標法

leetcode 141 判斷連結串列中是否有環 的思路是一樣的,通過設定快慢指標,從表頭開始遍歷,快指標每次走兩步,慢指標走一步。

當快指標到達連結串列尾時。慢指標剛好到達連結串列中點,返回慢指標即可

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public: ListNode* middleNode(ListNode* head) { ListNode* slow = head; ListNode* fast = head; while (fast && fast->next) //判斷非空條件 { slow = slow->next; fast = fast->next->next; } return slow; } };

原題連結: https://leetcode.com/problems/middle-of-the-linked-list/submissions/