链表的回文结构练习

请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false

回文结构,空间复杂度为O(1)的做法,首先利用快慢两个指针找到链表的中间点,之后将链表中间点之后的链表翻转,之后比较前面和后面的链表,如果全部相等返回true,如果不是返回false,理论上之后还应该恢复链表,但是要是判断回文结构可以不还原,代码如下:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Palindrome {
public:
    bool isPalindrome(ListNode* pHead) {
        if(!pHead)
            return false;
        if(!pHead->next)
            return true;
        ListNode* fast=pHead;
        ListNode* slow=pHead;
        ListNode* afterhead=NULL;
        while(fast)
            {
            if(fast->next&&!fast->next->next)
                {                
                reverselist(slow->next,afterhead);
                break;
            }
            else if(!fast->next)
                {                
                 reverselist(slow,afterhead);
                 break;
            }
            else
                {
                fast=fast->next->next;
                slow=slow->next;
            }                            
        }
        ListNode* temp=pHead;
        while(afterhead)
          {
            if(temp->val!=afterhead->val)
                return false;
            afterhead=afterhead->next;
            temp=temp->next;
          }
         return true;           
    }
    void reverselist(ListNode* head,ListNode* &afterhead)
        {
        ListNode* prehead=new ListNode(0);
        prehead->next=head;
        if(!head)
            return;
        if(!head->next)
            {
            afterhead=head;
            return;
        }
        ListNode* pre=prehead;
        ListNode* next=head->next;
        while(next)
            {
            head->next=pre;
            pre=head;
            head=next;
            next=next->next;
        }
        head->next=pre;
        afterhead=head;
        prehead->next->next=NULL;//让翻转后链表最后一个元素指向空。
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值