코딩테스트
10월 24일 - Remove Nth Node From End of List swift
알롱도담쓰
2023. 10. 24. 12:36
문제 설명
제한 조건
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.