본문 바로가기

Algorithm

[leetcode] 203. Remove Linked List Elements _ python3

203. Remove Linked List Elements

 

Remove Linked List Elements - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

풀이 코드

리스트의 노드를 탐색하면서 val에 해당하는 값이 나오면 해당 노드를 제거하면 된다. 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        if not head:
            return head
        
        node = head
        
        while node and node.next:
            if node.next.val == val:
                node.next = node.next.next
            else:
                node = node.next
                            
        if head.val == val:
            head = head.next

        return head