NASA 局長:美軍看見的 UFO 是什麼我也不知道
阿新 • • 發佈:2021-06-09
題目連結: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; } };