Palindrome Linked List
문제 설명
Given the head of a singly linked list, return true if it is a palindrome.
제한 사항
- The number of nodes in the list is in the range [1, 105].
- 0 <= Node.val <= 9
입출력 예
Example 1:

Input: head = [1,2,2,1] Output: true
Example 2:

Input: head = [1,2] Output: false
Python 코드
Python code
class Solution: def isPalindrome(self, head: ListNode) -> bool: val_list = [] curr = head while curr: val_list.append(curr.val) curr = curr.next return val_list == val_list[::-1]
* 참고 링크 : https://ceuity.tistory.com/12
C++ 코드
C ++ code
class Solution { public: bool isPalindrome(ListNode* head) { ListNode *slow = head, *fast = head, *prev, *temp; while (fast && fast->next) slow = slow->next, fast = fast->next->next; prev = slow, slow = slow->next, prev->next = NULL; while (slow) temp = slow->next, slow->next = prev, prev = slow, slow = temp; fast = head, slow = prev; while (slow) if (fast->val != slow->val) return false; else fast = fast->next, slow = slow->next; return true; } };
* 참고 링크 : https://dev.to/seanpgallivan/solution-palindrome-linked-list-5721
출처
https://leetcode.com/problems/palindrome-linked-list/submissions/
'코딩테스트 > Leet Code' 카테고리의 다른 글
[Leet Code] 27. Remove Element (0) | 2022.01.14 |
---|---|
[Leet Code] 20. Valid Parentheses (0) | 2022.01.14 |
[Leet Code] 136. Single Number (0) | 2022.01.13 |
[Leet Code] 118. Pascal's Triangle 다시 공부 ★ (0) | 2022.01.13 |
[Leet Code] 15. 3Sum 다시 공부 ★ (0) | 2022.01.13 |