c++算法题

c++算法题,第1张

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

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

 * };

 */

 ListNode* reverse(ListNode* head) {

        if(head == nullptr)

        return nullptr;

        ListNode* pre = nullptr;

        ListNode* cur = head;

        ListNode* next = head->next;

        while(cur){

            cur->next = pre;

            pre = cur;

            cur = next;

            if(next)

            next = next->next;

        }

        return pre;

    }

class Solution {

public:

    bool isPalindrome(ListNode* head) {

        ListNode* fast = head;

        ListNode* slow = head;

        while(fast&&fast->next){

            fast = fast->next->next;

            slow = slow->next;

        }

        ListNode* re = reverse(slow);

        while(head&&re){

            if(head->val!=re->val){

            return false;

}

            head = head->next;

            re = re->next;

        }

        return true;

    }

};.

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/3002940.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-27
下一篇 2022-09-27

发表评论

登录后才能评论

评论列表(0条)

保存