컴퓨터공학/알고리즘 문제 풀이

[LeetCode] 19. Remove Nth Node From End of List

TaeGyeong Lee 2023. 3. 16. 12:36

 

접근

  • 두 커서(Two pointer) 개념을 링크드 리스트 문제에 적용시켜 푸는 문제
  • 먼저 간 커서를 n 번 순회시켰을 때, None 인 경우와 그렇지 않은 경우를 모두 생각하여 솔루션을 작성해야 함
  • 가능한 케이스를 모두 면밀히 고민해 볼 필요가 있음

 

솔루션

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        
        cur_left, cur_right = head, head
        answer = cur_left

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

        if cur_right is None:
            return cur_left.next

        while cur_right.next:
            cur_right = cur_right.next
            cur_left = cur_left.next
        
        cur_left.next = cur_left.next.next

        return answer