floatFirstTOC: right
🖥️ 시작하며
주어진 연결 리스트가 팰린드롬(회문)인지 판별하는 문제다. 즉, 뒤집어도 같은 연결리스트가 되는지 확인하면 된다.
head
가 비어있다면 True로 판정
- 연결 리스트를 순회하면서 deque에 넣은 후, 양쪽 끝을 서로 판별
for i in range(length // 2): if queue[i] != queue[length - 1 - i]: return False
⚙️ Python
from collections import deque class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: if not head: # head가 비어있다면 return True queue = deque() # head가 빌 때까지 queue에 삽입 while head is not None: queue.append(head.val) head = head.next # 양쪽 끝으로 판별 length = len(queue) for i in range(length // 2): if queue[i] != queue[length - 1 - i]: return False return True
댓글