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

链表的回文结构

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList 
{
public:
    struct ListNode* ReverseNode(struct ListNode* phead)
    {
        struct ListNode* newhead = NULL,*next = NULL;
        struct ListNode* cur = phead;
        while(cur)
        {
            next = cur->next;
            cur->next = newhead;
            newhead = cur;
            cur = next;
        }
        return newhead;
    } 

    struct ListNode* MiddleNode(struct ListNode* phead)
    {
        struct ListNode*fast = phead,*slow = phead;
        while(fast && fast->next)
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }

    bool chkPalindrome(ListNode* head)
    {
       ListNode* mid = MiddleNode(head);
       ListNode* rmid = ReverseNode(mid);
       while(rmid)
       {
        if(head->val != rmid->val)
        {
            return false;
        }
        else
        {
            head = head->next;
            rmid = rmid->next;
        }
       }
       return true;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务