leetcode No234. Palindrome Linked List

Question

Given a singly linked list, determine if it is a palindrome.
判断链表是否为回文

Algorithm

需要解决的问题:
1、找到中心的位置(一快一慢指针,快的一次走两步,慢的一次走一步)
2、以中心拆分链表,并反转后半部分的链表
http://blog.csdn.net/u011391629/article/details/52164389

找到中心位置后,反转要分结点个数为奇数和偶数两种情况,也可以不分。

以1->2->3和1->2->3->4为例
如下图,奇数要反转slow->next,偶数要反转slow。
结束条件:fast!=NULL && fast->next!=NULL
这里写图片描述

如果是下图这种情况,就不用分奇数偶数的情况,反转slow->next就可以。
结束条件:fast->next!=NULL && fast->next->next!=NULL
这里写图片描述

Accepted Code:
不分奇偶:

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

分奇偶:

class Solution {
public:
    ListNode* reverseList(ListNode* head)
    {
        if(head==NULL || head->next==NULL)
            return head;
        ListNode* pre=NULL;
        ListNode* p=head;
        ListNode* pNext=NULL;
        while(p!=NULL)
        {
            pNext=p->next;
            p->next=pre;
            pre=p;
            p=pNext;
        }
        return pre;
    }
    bool isPalindrome(ListNode* head) {
        if(head==NULL || head->next==NULL)
            return true;
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast!=NULL && fast->next!=NULL)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        if(fast!=NULL)
        {
            slow=reverseList(slow->next);
        }
        else
        {
            slow=reverseList(slow);
        }
        while(slow!=NULL)
        {
            if(slow->val != head->val)
                return false;
            slow=slow->next;
            head=head->next;
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值