본문 바로가기
python-algorithm

leetcode 203. Remove Linked List Elements

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

https://leetcode.com/problems/remove-linked-list-elements/description/

 

Remove Linked List Elements - LeetCode

Can you solve this real interview question? Remove Linked List Elements - Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.   Example 1: [https://assets.leetcode.

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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]:
        answer = ListNode(-1)
        answer.next = head
        
        current_node = answer
        while current_node.next != None:
            if current_node.next.val == val:
                current_node.next = current_node.next.next
            else:
                current_node = current_node.next
                
        return answer.next
cs

answer라는 이름의 listnode를 만들어줍니다
'현재 노드' 기준에서 '다음 노드'가 val과 값이 같다면 그 노드는 연결하지 않고 그 '다음 다음 노드'와 연결합니다.
val과 값이 다르면 그대로 연결하면 됩니더

Create a listnode named answer
If the 'next node' in the 'current node' standard has the same value as val, that node is not connected and connected to the next 'next node'.
If the value is different from val, just connect it as it is.

반응형

댓글