876 連結串列中間節點
阿新 • • 發佈:2019-01-12
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; }