leetcode 234: Palindrome Linked List

To solve it with only O(1) space, you can only find the mid point of the linked list and do some reverse operation, so that you are able to traverse back. To find the mid point, use the fast and slow method, and once the mid point is found, reverse the latter half and compare.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *slow,*fast;
        slow=fast=head;
        while(fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        reverse(slow,fast);
        slow=head;
        while(fast)
        {
            if(slow->val!=fast->val)
                return false;
            slow=slow->next;
            fast=fast->next;
        }
        return true;
    }
    ListNode* reverse(ListNode* root,ListNode*& end)
    {
        if(!root||!root->next)
        {
            end=root;
            return root;
        }
        ListNode* temp=reverse(root->next,end);
        temp->next=root;
        root->next=NULL;
        return root;
    }
};


發佈了186 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章