Palindrome Linked List(迴文鏈表)

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

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

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(!head) return true;
        ListNode *fast=head,*slow=head,*p,*q=head;
        while(fast&&fast->next){
            fast=fast->next->next;
            slow=slow->next;
        }
       if(fast) p=reverseList(slow->next);
       else p=reverseList(slow);
       while(q&&p){
           if(q->val!=p->val) return false;
           q=q->next;
           p=p->next;
       }
       return true;
    }
    ListNode* reverseList(ListNode* head){
        if(!head) return NULL;
        ListNode *pre=new ListNode(-1);
        pre->next=head;

        while(head->next){
            ListNode *p=head->next;
            head->next=p->next;
            p->next=pre->next;//注意這裏不要寫成p->next=head;
            pre->next=p;

        }
        return pre->next;
    }
};
發佈了140 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章