[Simple Algorithm] 24. Palindromic Linked List

topic:

Check if a linked list is a palindrome.

Advanced:
Can you do it in O(n) time and O( 1 ) extra space?

Problem solving ideas:

1. Non-recursive. Copy the elements in the linked list directly to the array, and then compare whether the array is a palindrome.

2. Find the middle node of the linked list, start from the middle node, reverse the second half of the chat list, compare the first half and the second half of the linked list, and check whether the elements are equal in order.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL || head->next == NULL){
            return head;
        }
        
        ListNode * newHead = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        
        return newHead;
    }
    
    bool isPalindrome1(ListNode* head) {
       if(head == NULL || head->next == NULL){
           return true;
       }
       
       ListNode * tail = reverseList(head->next);
       if(tail->val != head->val){
           return false;
       }else{
           return isPalindrome(tail->next);
       }
        
    }
    
    int length(ListNode * head){
        int cnt = 0;
        while(head){
            head = head->next;
            cnt++;
        }
        
        return cnt;
    }
    
    bool isPalindrome(ListNode* head) {
        int len = length(head);
        int target = len%2?(len+1)/2:len/2;
        ListNode * slow = head;
        ListNode * fast = head;
        
        if(head == NULL || head->next == NULL){
            return true;
        }
        
        for(int i = 0;i < target;++i){
            head = head->next;
        }
        
        fast = reverseList(head);
        for(int i = 0;i < len/2;++i){
            if(fast->val != slow->val){
                return false;
            }else{
                fast = fast->next;
                slow = slow->next;
            }
        }
        
        return true;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325206931&siteId=291194637