본문 바로가기
python-algorithm

leetcode 234. Palindrome Linked List

by 무적김두칠 2023. 2. 11.

https://leetcode.com/problems/palindrome-linked-list/

 

Palindrome Linked List - LeetCode

Palindrome Linked List - Given the head of a singly linked list, return true if it is a palindrome or false otherwise.   Example 1: [https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg] Input: head = [1,2,2,1] Output: true Example 2: [https

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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: list = []
        if not head:
            return True
        
        node = head
        #convert linked list to list
        while node is not None:
            q.append(node.val)
            node = node.next
        
        # check wheter this is palindrome
        while len(q)>1:
            if q.pop(0)!=q.pop():
                return False
        
        return True
cs

line 9 , 첫번째 조건문에서는 linked list에 아무것도 없는 경우 -> True
Line 14 , 반복문에서는 linked list를 list로 변환합니다.
Line 19 , list의 가장 앞과 뒤를 pop 해주면서 다를경우는 False 를 리턴합니다.
LIne 23, 여기까지 아무 문제 없으면 True를 리턴합니다.

line 9 , in the first condition, if there is nothing in the linked list -> True


Line 14 , the loop converts the linked list into a list.
Line 19, pops the top and bottom of the list, and returns False if they are different.
Line 23, returns True if there is no problem up to this point.

반응형

댓글