Description:

Given the head of a singly linked list, return true if it is a palindrome.

Example 1:

Input: head = [1,2,2,1] 
Output: true

Example 2:

Input: head = [1,2]
Output: false

Naive Solution

Idea

Put the whole linked list into an array.

Check with the index from both sides of the array.

Code

bool isPalindrome(struct ListNode* head){
    int l[100000];
    int cnt=0, i;
    struct ListNode* p = head;
    
    while(p->next != NULL){
        l[cnt] = p->val;
        p = p->next;
        cnt+=1;
    }
    
    l[cnt] = p->val;
    for(i=0; i<=cnt/2; ++i){
        if(l[i] != l[cnt-i]) return false;
    }
    return true;
}

With O(1) space

Idea

Use pointer to invert half of the linked list

  1. Use the fast and slow pointers to find the middle of the linked list out
  2. Reverse half of the list

Then iterate it.

  1. Use two pointers to iter through the linked list from begin of the linked list and the middle of the linked list

Code

bool isPalindrome(struct ListNode* head){
    struct ListNode *fast, *slow;
    fast = head; slow = head;
    
    while( fast != NULL && fast->next != NULL ){
        slow = slow->next;
        fast = fast->next->next;
    }
    
    struct ListNode *cur = slow, *pre = NULL, *tmp = NULL;
    
    while(cur != NULL){
        tmp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = tmp;
    }
    
    slow = head; fast = pre;
    while(fast != NULL && slow != NULL){
        if (fast->val != slow->val) {return false;}
        fast = fast->next;
        slow = slow->next;
    }
    return true;
}