[LeetCode]Palindrome Linked List

来源:互联网 发布:linux x86 x64区别 编辑:程序博客网 时间:2024/06/03 07:29

题目:判断一个单链表是不是回文, O(n) time and O(1) space

分析:使用龟兔法找到链表的中心,反转后半段链表,然后与前半段比较

参考代码:

bool isPalindrome(struct ListNode* head) {
     struct ListNode* fast,*slow,*pre,*cur,*ne;
    fast=slow=head;
    if(!head||!head->next)
    {
            return true;
    }
     while(fast&&fast->next)
    {
        slow=slow->next;
        fast=fast->next->next;
    }
     if(fast)
    {
        slow=slow->next;
        pre=slow;
        cur=pre->next;
        while(cur)
        {
            ne=cur->next;
            cur->next=pre;
            pre=cur;
            cur=ne;
        }
        slow->next=NULL;
        slow=pre;
        
       
    }else{
        
        pre=slow;
        cur=pre->next;
        while(cur)
        {
            ne=cur->next;
            cur->next=pre;
            pre=cur;
            cur=ne;
        }
        slow->next=NULL;
        slow=pre;
    }
     cur=head;
    while(slow&&cur)
    {
        if(cur->val!=slow->val)
        return false;
        else {
            cur=cur->next;
            slow=slow->next;
        }
    }
    return true;
    
}


0 0
原创粉丝点击