티스토리 뷰

문제 설명

제한 조건

https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/603/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

내 답안

class Solution {
    func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
        var firstHead = head
        var secondHead = head
        var prev: ListNode? = nil
        
        for _ in 1...n {
            firstHead = firstHead?.next
        }
        
        while firstHead != nil {
            firstHead = firstHead?.next
            prev = secondHead
            secondHead = secondHead?.next
        }
        
        if prev == nil {
            return head?.next
        }
        
        prev?.next = secondHead?.next
        
        return head
    }
}

접근 방법

사이트에서 제공한 힌트 :

Maintain two pointers and update one with a delay of n steps.
 
 

다른 풀이

알게 된 것

최근에 올라온 글