【easy】234. Palindrome Linked List

ques: 判断一个链表是否回文 Could you do it in O(n) time and O(1) space?

method:先将链表分为两部分,将后半部分反转,最后从前往后判断是否相等。

topic: 链表,链表反转

/** 
 * Definition for singly-linked list. 
 * public class ListNode { 
 *     int val; 
 *     ListNode next; 
 *     ListNode(int x) { val = x; } 
 * } 
 */  

class Solution {
public:
     bool isPalindrome(ListNode *head) { 
        //input check  abcba abccba  
        if(head == NULL || (head&&head->next==NULL)) return true;  
          
        ListNode *middle = partition(head);  
        middle = reverse(middle);  
          
        while(head!=NULL && middle!=NULL) {  
            if(head->val != middle->val) return false;  
            head = head->next;  
            middle = middle->next;  
        }  
        return true;  
    }  
private: 
    ListNode* partition(ListNode *head) {  
        ListNode* p = head;  
        while(p&&p->next!=NULL && p->next->next!=NULL) {  
            p = p->next->next;  
            head = head->next;  
        }  
          
        p = head->next;  
        head->next = NULL;  
        return p;  
    }  
private: 
    ListNode* reverse(ListNode *head) {  
        if(head==NULL || head->next==NULL) return head;  
        ListNode* pre = head;  
        ListNode* cur = head->next;  
        pre->next = NULL;  
        ListNode* nxt = NULL;  
          
        while(cur!=NULL) {  
            nxt = cur->next;  
            cur->next = pre;  
            pre = cur;  
            cur = nxt;  
        }  
        return pre;  
    }  
};

 

posted @ 2018-01-08 22:04  Sherry_Yang  阅读(82)  评论(0编辑  收藏  举报