오늘도 개발

36. Remove Linked List Elements 본문

자료구조 & 알고리즘/Leetcode

36. Remove Linked List Elements

Sueeeeeee 2022. 10. 24. 11:35

문제

val을 인수로 받아 연결 리스트에서 val값만 삭제하시오.

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

 

해결 방법

https://leetcode.com/problems/remove-linked-list-elements/discuss/57461/Simple-and-clear-python-solution

def removeElements(head, val):
    # 첫 번째 노드가 val인 경우 head를 다음 노드로 지정
    while head and head.val == val:
            head = head.next
            
    current = head

    while current and current.next:
        if current.next.val == val:
            current.next = current.next.next
        else:
            current = current.next

    return head

'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글

38. Number of Islands(bfs, dfs)  (0) 2022.10.27
37. Design Circular Queue  (0) 2022.10.26
35. Reverse Linked List  (0) 2022.10.24
34. Remove Nth Node From End of List  (0) 2022.10.21
33. Intersection of Two Linked Lists  (0) 2022.10.21