본문 바로가기
알고리즘/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;
    }
};

'알고리즘 > leetcode' 카테고리의 다른 글

437. Path Sum III  (0) 2022.08.14
1706. Where Will the Ball Fall  (0) 2022.07.31
14. Longest Common Prefix  (0) 2022.07.30
202. Happy Number  (0) 2022.07.27
189. Rotate Array  (0) 2022.07.24