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

链表的回文结构

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
#include <algorithm>
#include <cstddef>
class PalindromeList {
  public:

    struct ListNode* reverse(struct ListNode* head) {
        struct ListNode* newHead = NULL;
        struct ListNode* pcur = head;
        while (pcur) {
            struct ListNode* next = pcur->next;//建议画图理解,类似于头插
            pcur->next = newHead;
            newHead = pcur;
            pcur =  next;
        }
        return newHead;
    }

    struct ListNode* find(struct ListNode* head)//利用的快慢指针
    {
        struct ListNode* fast=head;
        struct ListNode* slow=head;
        while(fast&&fast->next)
        {
            fast=fast->next->next;//fase一次走两步
            slow=slow->next;//slow一次走一步
        }
        return slow;//到最后fast走过的路程是slow走过的路程的两倍,slow自然是中点(偶数中点为用两个中间值其中的靠后的那个)
    }
    bool chkPalindrome(ListNode* A) {
        // write code here
        struct ListNode* mid = find(A);//find函数找到链表的中间值返回给mid
        mid = reverse(mid);//reverse函数把mid为头节点的新链表逆置,再把逆置过后的指针返回给mid
        while(mid)
        {
            if(A->val!=mid->val)//判断二者是否相等,若不相等,则返回false
            {
                return false;
            }
            mid=mid->next;//mid 和 A 往后走(可以定义pcur来代替A遍历,防止改变原链表)
            A=A->next;
        }
        return true;//遍历完后,若都相等则返回true

    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-29 17:30
找实习找着找着就要进入7月了,马上秋招也要开始了,找实习还有意义吗?
绝迹的星:有面就面, 没面上就当日薪4位数大佬免费培训, 面上了再考虑要不要实习
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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