알고리즘/leetcode
234. Palindrome Linked List
by 유이얼
2022. 7. 30.
/**
* 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 *reverse(ListNode *cur) {
ListNode *prev = nullptr;
while (cur) {
ListNode *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
bool isPalindrome(ListNode* head) {
auto fast = head, slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
if (fast) slow = slow->next;
slow = reverse(slow);
while (slow) {
if (head->val != slow->val) return false;
head = head->next;
slow = slow->next;
}
return true;
}
};