19. Remove Nth Node From End of List

Taesoo Kim·2023년 1월 9일
0

CrackingAlgorithm

목록 보기
10/36

19. Remove Nth Node From End of List

투포인터의 난이도가 올라간다.

짧게 문제를 설명하자면, linked list에서 두에서 n번째 노드를 제거한 리스트를 반환하라는 아주 간단한 문제이다.
문제 접근이 어려워서 한 30분 고민하다 힌트를 봤는데, 새로운 유형의 투포인트인것 같다.

# 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]:
        start = head
        end = head

        for i in range(n):
            end = end.next

        if not end:
            return head.next

        while end.next:
            start = start.next
            end = end.next
        start.next = start.next.next
        return head

        

로직은 생각보다 간단한데, start포인터를 end보다 n만큼 늦게 출발시키는거다. 그럼 end가 리스트 끝에 도달했을때, start는 우리가 찾는 노드의 앞에서 멈추게 된다. 이후 start의 다음 노드를 start.next.next로 꽂아주면 문제 끝.

투포인터는 양 끝에서 점차 다가와 만난다거나, 같은 쪽에서 하나만 계속 전진시키고, 조건에 따라 다른 포인터를 움직이는 문제들만 봐왔었는데, 새로운 문제를 만나니 조금 헤매는것 같다.

profile
SailingToTheMoooon

0개의 댓글