풀이 1)
# 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
풀이 2)
# 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:
q = collections.deque()
if not head:
return True
node = head
while node is not None:
q.append(node.val)
node = node.next
while len(q) > 1:
if q.pop() != q.popleft():
return False
return True
'자료구조와 알고리즘' 카테고리의 다른 글
206. Reversed Linked List(역순 연결 리스트) (0) | 2023.02.08 |
---|---|
21. Merge Two Sorted Lists(두 정렬 리스트의 병합) (0) | 2023.02.06 |
121. Best Time to Buy and Sell Stock(주식을 사고팔기 가장 좋은 시점) (0) | 2023.02.03 |
238. Product of Array Except self(자신을 제외한 배열의 곱) (0) | 2023.02.03 |
561. Array Partition I(배열 파티션 I) (0) | 2023.02.02 |