1. 程式人生 > >234 迴文連結串列

234 迴文連結串列

ListNode *reverse(ListNode *head) {
    ListNode *front = head, *rear = nullptr, *temp = nullptr;
    while (front != nullptr) {
        temp = front->next;
        front->next = rear;
        rear = front;
        front = temp;
    }
    return rear;
}

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

bool isPalindrome(ListNode *head) {
    ListNode *mid = middleNode(head);
    ListNode *re = reverse(mid);
    while (re != nullptr) {
        if (re->val != head->val)
            return false;
        re = re->next;
        head = head->next;
    }
    return true;
}