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

链表的回文结构

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
struct ListNode* reverseList(struct ListNode* head) {
    if(head == NULL)
        return NULL;
    struct ListNode* n1 = NULL, *n2 = head, *n3 = head->next;

    while(n2)
    {
        n2->next = n1;
        n1 = n2; 
        n2 = n3;
        if(n3)
            n3 = n3->next;
    }
    return n1;
}
struct ListNode* middleNode(struct ListNode* head) {
    struct ListNode* slow = head, *fast = head;
    while(fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}
class PalindromeList {
public:
    bool chkPalindrome(ListNode* phead) {
        // write code here
        struct ListNode* mid = middleNode(phead);
        mid = reverseList(mid);
        while(mid && phead)
        {
            if(phead->val != mid->val)
            {
                return false;
            }
            else {
            phead = phead->next;
            mid = mid->next;
            }
        }
        return true;
    }
};

全部评论

相关推荐

LZHR:老哥你从投递简历测评完到一面中间隔了多久呀,我这边已经过了五天了仍显示简历筛选中是不是就是挂了
腾讯求职进展汇总
点赞 评论 收藏
分享
27届学院本誓死冲击...:自我评价和校园经历全删了,荣誉经历只留奖学金,项目也全得换都不如外卖
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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