본문으로 바로가기

[Leet code] 234. Palindrome Linked List

category ps/자료구조 2021. 11. 26. 23:42
Categoryps/자료구조
Tag자료구조
Tagslinked listrunner
난이도★★
발행 여부
사이트Leet code
실수 유형
이해이해 안되는 부분 있음
최종 편집 일시
푼 날짜

문제 해설 및 주의사항

원문

Given the head of a singly linked list, return true if it is a palindrome.

Example 1:

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

Example 2:

Input: head = [1,2]
Output: false

번역 및 주의사항

1→2→2→1 라는 list 가 들어오면, palindrome 인지 판별하여 true or false 반환하라.

Constraints:

  • The number of nodes in the list is in the range [1, 10^5].
  • 0 <= Node.val <= 9


풀이

내 풀이 코드 (deque)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        if not head:
            return True
        node = head
        deq = collections.deque()
        while node :
            deq.append(node.val)
            node = node.next
        
        while len(deq) >= 2:
            if deq.pop() != deq.popleft():
                return False
        
        return True

풀이 코드 (책) (Runner)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        rev = None
        slow = fast = head
        # 런너를 이용해 역순 연결 리스트 구성
        while fast and fast.next:
            fast = fast.next.next
            rev, rev.next, slow = slow, rev, slow.next
        if fast:
            slow = slow.next


        # 팰린드롬 여부 확인
        while rev and rev.val == slow.val:
            slow, rev = slow.next, rev.next
        return not rev
  • rev, rev.next, slow = slow, rev, slow.next 이 구문이 상당히 중요하다.
    • 다중 할당에 대해서 잘 이해해야 한다.


퇴고

반응형

'ps > 자료구조' 카테고리의 다른 글

[프로그래머스] 베스트앨범  (0) 2021.12.12
[프로그래머스] 주식가격  (0) 2021.12.12
[Leet code] 21. Merge Two Sorted Lists  (0) 2021.11.26
[Leet code] 20. Valid Parentheses  (0) 2021.11.26
[Leet code] 739. Daily Temperatures  (0) 2021.11.26