1. 程式人生 > 遊戲攻略 >《原神攻略》愈療試煉怎麼過?愈療試煉過關心得分享

《原神攻略》愈療試煉怎麼過?愈療試煉過關心得分享

題目連結:https://leetcode-cn.com/problems/palindrome-linked-list/
題目描述:

題解:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* node)
    {
        ListNode *pre = nullptr;
        ListNode *cur = node;
        ListNode *tail;
        while(cur != nullptr)
        {
            tail = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tail;
        }
        return pre;
    }
    bool isPalindrome(ListNode* head) {
        if(!head || !head->next)
            return true;
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* prev;
        //快慢指標找中點
        while(fast != nullptr && fast->next != nullptr)
        {
            slow = slow->next; 
            fast = fast->next->next;
        }
        //連結串列節點奇偶處理
        if(fast != nullptr)
            prev = slow->next;
        else
            prev = slow;
        //後半部節點反轉
        prev = reverseList(prev);
        while(prev && head)
        {
            if(head->val != prev->val)
                return false;
            head = head->next;
            prev = prev->next;

        }
        return true;
    }
};