2023年1月14日 星期六

876. Middle of the Linked List

解題思路

因為 slow pointer 走的速度會是 fast pointer 的兩倍,正好用來找中間 node。

程式碼

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode* slow = head;
        ListNode* fast = head;

        while(fast != nullptr && fast->next != nullptr)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};

沒有留言:

張貼留言