Linked List Palindrome

1) slow fast pointer - find middle

2) reverse linked list - reverse what behind the middle

3) cal length - cal length to define the loop length

4) two pointers compare

code


/**
 * 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) {
        if(head == NULL)
        {
            return true;
        }

        ListNode* s = head;
        ListNode* f = head->next;
        while(f != NULL && f->next != NULL)
        {
            s = s->next;
            f = f->next->next;
        }

        int n = countLength(head);
        ListNode* shadow = n%2==0?reverse(s):reverse(s->next);

        for(int i = 0; i<n/2; i++)
        {
            if(head->val != shadow->val)
            {
                return false;
            }
            head = head->next;
            shadow = shadow->next;
        }

        return true;
    }

    int countLength(ListNode* head)
    {
        if(head == NULL)
        {
            return 0;
        }

        int ret = 0;
        while(head != NULL)
        {
            ret++;
            head = head->next;
        }
        return ret;
    }

    ListNode* reverse(ListNode* head)
    {
        if(head == NULL)
        {
            return head;
        }

        ListNode* p = NULL;
        while(head != NULL)
        {
            ListNode* next = head->next;
            head->next = p;
            p = head;
            head = next;
        }

        return p;
    }
};

results matching ""

    No results matching ""