876.Middle of the Linked List

1.問題

2.想法

  • 快慢指針

3.程式碼

/**
 * 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) {
        if (!head || !head->next) {
            return head;
        }
        
        ListNode *first = head, *second = head;
        
        while (second && second->next) {
            first = first->next;
            second = second->next->next;
        }
        
        return first;
    }
};

Last updated