→ Problems

[Algorithm] LeetCode - Remove Nth Node From End of List

Swift librarian 2025. 5. 12. 21:49

📠 문제

  • Remove Nth Node From End of List
  • 난이도: Medium
  • 연결리스트에서 끝에서 n번째의 요소를 제거하는 문제
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

💡 풀이

요즘 연결리스트 문제를 자주 푸는 것 같다. 이 문제는 먼저 n번 노드를 뒤로 보낸 후에 같이 이동하면서 next가 nil이면 start.next = start.next.next 로 연결을 끊어주면 된다.

func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
    let zero: ListNode? = ListNode(0)
    zero?.next = head

    var start = zero
    var end = zero

    for _ in 0..<n {
        end = end?.next
    }

    while let next = end?.next {
        start = start?.next
        end = next
    }

    start?.next = start?.next?.next

    return zero?.next
}

Runtime에서 좋은 결과를 얻을 수 있었다.