234. Palindrome Linked List

https://www.cnblogs.com/grandyang/p/4635425.html

错误代码:

while(last->next){
            ListNode* tmp = last->next;
            last->next = tmp->next;
            slow->next = tmp;
            tmp->next = last;
        }

这个代码之后保证第一次,第二次反转就错了

 

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return true;
        ListNode *slow = head,*fast = head;
        while(fast->next && fast->next->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* last = slow->next;
        while(last->next){
            ListNode* tmp = last->next;
            last->next = tmp->next;
            tmp->next = slow->next;
            slow->next = tmp;
        }
        ListNode* pre = head;
        while(slow->next){
            slow = slow->next;
            if(slow->val != pre->val)
                return false;
            pre = pre->next;
        }
        return true;
    }
};

 

posted @ 2019-03-07 11:48  有梦就要去实现他  阅读(85)  评论(0编辑  收藏  举报