본문 바로가기

Python 문법 정복하기

[Python] LinkedList 예제 (Palindrome)

주어진 리스트가 팰린드롬인지 판별하는 프로그램을 작성하세요.

     

   

     예시1) [1, 2, 2, 1] ⇒ True

     예시2) [1, 2] ⇒ False

 

 

test.python

from structures import LinkedList


l1 = LinkedList()
for num in [1, 2, 2, 1]:
    l1.append(num)

l2 = LinkedList()
for num in [1, 2]:
    l2.append(num)


assert isPalindrome(l1)
assert not isPalindrome(l2)

 

 

practice.python

def isPalindrome(ln):
    arr = []
    head = ln.head

    if not head:
        return True

    node = head
    while node:
        arr.append(node.val)
        node = node.next

    while len(arr) > 1:
        first = arr.pop(0)
        last = arr.pop()
        if first != last:
            return False

    return True

'Python 문법 정복하기' 카테고리의 다른 글

[Python] Tree  (0) 2024.04.10
[Python] HashTable (Chaining, Open Addressing)  (0) 2024.03.24
[Python] Queue 예제 (Josephus)  (0) 2024.03.23
[Python] Queue (FIFO)  (0) 2024.03.23
[Python] Array & LinkedList  (1) 2024.03.23