Python 문제풀이/LeetCode
19. Remove Nth Node From End of List ** (링크드 리스트)
hjc_
2022. 6. 16. 16:24
링크드리스트가 주어지면 끝에서 n번째 노드를 삭제하고 반환하라.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
# 더미노드를 활용하여 edge case 제거
dummy=ListNode(-1)
dummy.next=head
slow=dummy
fast=dummy
# n 만큼의 노드 갭 설정
for i in range(n):
fast = fast.next
while fast.next != None :
slow=slow.next
fast=fast.next
# 삭제
slow.next = slow.next.next
return dummy.next
참고