leetcode 234. Palindrome Linked List

快慢指针找到中点,反转后半段,比较。

其实慢指针走的时候就可以开始反转。

    bool isPalindrome(ListNode* head) {
        if (head == NULL || head->next == NULL)
            return true;
        if (head->next->next == NULL)
            return head->val == head->next->val;
        ListNode* fast = head;
        ListNode* slow = head;
        
        while (fast) {
            fast = fast->next;
            if (!fast) {
                slow = slow->next;
                break;
            }
            fast = fast->next;
            slow = slow->next;
        }
        slow = invertList(slow);
        while (slow) {
            if (head->val != slow->val)
                return false;
            head = head->next;
            slow = slow->next;
        }
        return true;
    }
    
    ListNode* invertList(ListNode* root) {
        ListNode* ret = NULL;
        while (root) {
            ListNode* temp = root->next;
            root->next = ret;
            ret = root;
            root = temp;
        }
        return ret;
    }

 

posted on 2018-02-06 14:20  willaty  阅读(103)  评论(0编辑  收藏  举报

导航