https://leetcode.com/problems/palindrome-linked-list/
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.
반응형
'python-algorithm' 카테고리의 다른 글
leetcode 21. Merge Two Sorted Lists (0) | 2023.02.13 |
---|---|
leetcode 1523. Count Odd Numbers in an Interval Range (0) | 2023.02.13 |
leetcode 121. Best Time to Buy and Sell Stock (0) | 2023.02.11 |
leetcode 2149. Rearrange Array Elements by Sign (0) | 2023.02.10 |
leetcode 238. Product of Array Except Self (0) | 2023.02.10 |
댓글