Try   HackMD

【LeetCode】 876. Middle of the Linked List

Description

Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Note:
The number of nodes in the given list will be between 1 and 100.

給一個非空的、單獨的linked list的開頭head,回傳最中間的節點。
如果有兩個中間點,回傳第二個點。
注意:
點的數量只會介於1到100之間。

Example:

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.

Solution

  • 這題很基礎也蠻常考的,強烈建議可以好好記起來。
  • 如果先算list的長度再重跑,要跑1.5l,這樣實在太慢了。
  • 最好的方法是有兩個點一起跑,第一個一次跑一步,第二個一次跑兩步。
  • 當第二個點看到尾巴時,第一個點就是中間點。
  • 特別注意點的數量為單數和雙數時要分別處理。

Code

/** * 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* one = head; ListNode* two = head; while(1) { if(two->next == NULL) return one; if(two->next->next == NULL) return one->next; one = one->next; two = two->next->next; } } };
tags: LeetCode C++