Problem Solving/LeetCode

[LeetCode] C++ 234. Palindrome Linked List

LeeJaeJun 2024. 8. 16. 21:51
728x90
반응형

https://leetcode.com/problems/palindrome-linked-list/description/

 

문제

 

문제 분석

- Linked List의 값들을 다른 자료형에 옮겨서 양 끝을 하나씩 검사하는 방식으로 palindrome을 검사할 수 있을 것입니다. 양 끝에서만 접근이 이루어지기 때문에 Deque를 쓰는 것이 가장 효율적이라고 생각했습니다.

- Runner 기법을 사용하여 구현한다면 모든 ListNode를 다른 자료형에 넣지 않고도 검사할 수 있을 것 입니다. 절반까지만 딱 읽어드리면서 그 절반을 reverse한 Linked List를 만들고, 이걸 남은 절반과 비교하면 됩니다.

 

풀이 1 (Deque)

/**
 * 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 {
private:
    std::deque<int> deq;
public:
    bool isPalindrome(ListNode* head) {
        if (!head || !head->next) {
            return true;
        }

        ListNode* current = head;
        
        while(current != nullptr){
            deq.push_back(current->val);
            current = current->next;
        }

        while(deq.size() > 1){
            if (deq.front() != deq.back()){
                return false;
            }

            deq.pop_front();
            deq.pop_back();
        }
        return true;
    }
};

풀이 2(Runner)

/**
 * 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) {
        if (!head || !head->next) {
            return true;
        }

        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* prev = nullptr;
        while(fast && fast->next){
            fast = fast->next->next;
            ListNode* next_slow = slow->next;
            slow->next = prev;
            prev = slow;
            slow = next_slow;
        }

        if(fast){
            slow = slow->next;
        }

        while(prev && slow){
            if(prev->val != slow->val){
                return false;
            }

            prev = prev->next;
            slow = slow->next;
        }

        return true;
    }
};

 

728x90
반응형