Tuesday, August 11, 2015

[LeetCode] Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */


class Solution {
    ListNode *reverse(ListNode *node)
    {
        ListNode *res = NULL;
        while(node)
        {
            ListNode *t = node->next;
            node->next = res;
            res = node;
            node = t;
        }
        return res;
    }
public:
    bool isPalindrome(ListNode* head) {
        if(!head) return true;
        
        ListNode *slow = head, *fast = head;
        while(fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }

        if(fast) slow = slow->next;

        slow = reverse(slow);
        
        while(slow && head)
        {
            if(slow->val != head->val) return false;
            slow = slow->next;
            head = head->next;
        }
        return true;
    }
};