题解 | #链表的回文结构#

链表的回文结构

https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        typedef struct ListNode ListNode;
        // write code here
        //先逆置,再比较。
         //先快慢指针法找中点
         ListNode* slow=A;
         ListNode* fast=A;
        while(fast&&fast->next){
            slow=slow->next;
            fast=fast->next->next;
        }
        //开始逆置
        ListNode* cur=slow,*head=slow;
        ListNode* pre=cur->next;
        cur->next=nullptr;
        while(pre){
            cur=pre;
            pre=pre->next;
            cur->next=head;
            head=cur;
        }
        //开始比较
        for(ListNode* a=A;cur;cur=cur->next,a=a->next){
            if(a->val!=cur->val){
                  return false;
            }
        }
        return true;
    }
};

先用快慢指针找到中点,再从中点开始让后半段逆置,接着就可以一个一个比较了。

全部评论

相关推荐

程序员小白条:找的太晚,别人都是大三实习,然后大四秋招春招的,你大四下了才去实习,晚1年
点赞 评论 收藏
分享
迟缓的斜杠青年巴比Q...:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务