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;
}
posted @ 2019-01-12 18:14  INnoVation-V2  阅读(93)  评论(0编辑  收藏  举报