본문 바로가기
Algorithm/LeetCode

[LeetCode] 234. Palindrome Linked List (C++)

by shine-jung 2021. 7. 31.
반응형

문제 링크

 

코딩하기 전 생각하기

/*
Linked List를 traverse 하면서 배열로 변환한다.
순서를 반전 시킨 배열과 기존 배열을 비교하여
같으면 true를,
다르면 false를 반환한다.
*/

 


 

코드

/**
 * 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) {
        string s = "";
        while ( head != nullptr ) {
            s += to_string(head->val);
            head = head->next;
        }
        string t = s;
        reverse(t.begin(), t.end());
        if ( t == s ) return true;
        return false;
    }
};

 


 

느낀점

 

Doubly Linked List 였으면 tail에서 head로 가는 값과 head에서 tail로 가는 값을 비교했을 것인데

Singly Linked List여서 문자열의 reverse 기능을 사용하였다.

 

(주의) 기록용으로 작성한 글입니다. 코드가 허접하거나 알고리즘의 효율이 낮을 수 있습니다.

댓글 환영합니다!

반응형

댓글