Developer/LEETCODE
234. Palindrome Linked List
cepiloth
2021. 9. 4. 11:34
728x90
https://leetcode.com/problems/palindrome-linked-list/
Palindrome Linked List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
난이도 : easy

문제
연결 리스트가 팰린드롬 구조인지 판별하라.
deque 자료형을 이용해서 문제를 풀었다.
코드
ListNode 의 모든 원소를 deque 에 삽입하고 front 와 back 을 비교하여 같으면 원소를 양쪽 원소를 pop 해주고 순회하도록 하였다.
/**
* 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) {
deque<int> q;
ListNode* ptr = head;
while(ptr!=NULL)
{
q.push_front(ptr->val);
ptr = ptr->next;
}
while(!q.empty())
{
if(q.front()!=q.back())
return false;
q.pop_front();
if(q.empty()) return true;
q.pop_back();
}
return true;
}
};
728x90
반응형