/**
* 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:
bool isPalindrome(ListNode* head) {
ListNode *fast = head, *slow = head;
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}
// fast不为nullptr,说明链表有奇数个节点
if (fast != nullptr) {
slow = slow->next;
}
slow = reverseList(slow);
fast = head;
while (slow != nullptr) {
if (slow->val != fast->val) {
return false;
}
slow = slow->next;
fast = fast->next;
}
return true;
}
ListNode* reverseList(ListNode *head) {
ListNode *prev = nullptr, *curr = head;
while (curr != nullptr) {
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
leetcode 234. 回文链表
最新推荐文章于 2024-08-30 17:03:53 发布