코딩 공부/Leetcode
[Python] 19. Remove Nth Node From End of List
일하는 공학도
2025. 2. 10. 16:44
728x90
난이도 : medium
끝에서 n번째 node를 삭제한 linked list를 return하는 문제
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
cur = head
num = 0
while cur:
num += 1
cur = cur.next
target = num - n
if target == 0:
head = head.next
return head
cur = head
for _ in range(target - 1):
if not cur.next:
return
cur = cur.next
cur.next = cur.next.next
return head
- cur를 끝까지 이동하면서 linked list의 길이를 num으로 계산
- 지우고자 하는 target 위치를 설정
- target이 맨 앞이면, head를 바로 다음 node로 update
- 제거할 node의 이전 node로 이동
- cur.next = cur.next.next로 이전 node가 다음 node를 건너뛰도록 설정
Runtime : 0ms
Memory : 17.86MB (28.63%)
728x90