876 链表中间节点

  ListNode* middleNode(ListNode* head) {
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }

自己写的不够简洁

ListNode *middleNode(ListNode *head) {
    if (head == nullptr || head->next == nullptr)
        return head;
    ListNode *slow = head, *fast = head->next;
    while (fast->next != nullptr) {
        fast = fast->next;
        slow = slow->next;
        if (fast->next == nullptr)
            return slow;
        fast = fast->next;
    }
    return slow->next;
}
posted @ 2019-01-12 18:02  INnoVation-V2  阅读(100)  评论(0编辑  收藏  举报