본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 19. Remove Nth Node From End of List

반응형

Remove Nth Node From End of List

Difficulty: Medium


Given the head of a linked list, remove the nth node from the end of the list and return its head.

 

Example 1:

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

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

 

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

 

Follow up: Could you do this in one pass?

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(-1, head)
        first, second = dummy, dummy

        for _ in range(n + 1) :
            first = first.next

        while first :
            first = first.next
            second = second.next

        second.next = second.next.next

        return dummy.next

이런 문제는 더미 노드를 하나 만들어 원본데이터가 손실되지 않도록 하자.

Two Pointer 를 설정한다. 여기서 first, second가 Two Pointer가 된다. 모두 dummy 인 -1 에서 시작을 하게 된다. 

first 를 n+1칸 앞으로 이동시킨다. 이렇게 하면 first가 끝(None)에 도달했을 때, second는 삭제할 노드의 바로 앞 노드에 위치하게 된다. 

이제 둘 다 동시에 이동을 시키면서 first가 끝에 도달하게 되면 second는 삭제할 노드 바로 앞에 위치하게 된다.

이제 삭제를 하자. second.next = second.next.next는 삭제할 노드를 건너뛰어 삭제를 한다. 

 

반응형