[LeetCode] 30.Linked List - Palindrome Linked List palindrome list

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

Palindrome initially did not understand what it means, then Baidu a wave. In summary, the palindrome is a symmetrical meaning.

Due to the nature of the list, only one way to go black (bottom), can not go back. I think the first half of the list to the inverse position, one by one and then compared to the corresponding portion of the second half. There is also need to consider the parity situation.

/**
 * 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* p = head;
        if(head==NULL) return true;
        ListNode* q = head->next;
        if(q==NULL) return true;
        int counter = 0;
        int counter1 = 0 ;
         the while (! P = NULL)   // Get the length of the list 
        { 
            counter ++ ; 
            P = p-> Next; 
        } 
        P = head;  
         // start Retrograde first half 
        counter1 = counter / 2 ;
         the while (- -counter1)      // starts the first half Retrograde list 
        { 
            P -> = Q- Next> Next; 
            Q -> Next = head; 
            head = Q; 
            Q = p->Next; 
        } 
        IF (counter% 2 == 0 )    // chain length of even-numbered 
        {
             the while (Q =! NULL) 
            { 
                IF (head-> Val Q- ==> Val) 
                { 
                    head = head-> Next; 
                    Q = Q-> Next;
                     Continue ; 
                } 
                the else  return  to false ; 
            } 
            return  to true ; 
        } 
        the else      // list of odd length 
         {
            q=q->next;
            while(q!=NULL)
            {
                if(head->val==q->val)
                {
                    head=head->next;
                    q=q->next;
                    continue;
                }
                else return false;
            }
            return true;
        }
    }
};

 

Guess you like

Origin www.cnblogs.com/hu-19941213/p/11441567.html