0
点赞
收藏
分享

微信扫一扫

SpringCache缓存专题

8052cf60ff5c 2024-02-27 阅读 9

1.题目链接:
LINK
2.详解思路:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/



//找到中间结点
struct ListNode* middleNode(struct ListNode* head) {
    //思路2:快慢指针法

    struct ListNode* fast = head;
    struct ListNode* slow = head;

    while(fast && fast->next)//快指针走到头
    {
        slow = slow->next;
        fast = fast->next->next;
    }

    return slow;

}


struct ListNode* reverseList(struct ListNode* head)
{
    //逆置链表为空
    if(head == nullptr) 
    return head;

    //不为空
    struct ListNode* n1 = nullptr;
    struct ListNode* n2 = head;
    struct ListNode* n3 = head->next;

    while(n2)
    {
        //逆置
        n2->next = n1;

        n1 = n2;
        n2 = n3;
        if(n3)//n3不为空
        {
            n3 = n3->next;
        }
    }

    return n1;

}

class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        // write code here
        //找到中间节点
        struct ListNode* pMidNode = middleNode(A);
        //逆置中间节点及其以后的节点
        struct ListNode* pNewMidNode = reverseList(pMidNode);
        //对比
        while(A&&pNewMidNode)
        {
            if(pNewMidNode->val!=A->val)
            {
                return false;
            }
            //向后走
            A = A->next;
            pNewMidNode = pNewMidNode->next;
        }

        return true;

    }
};

完。

举报

相关推荐

0 条评论