Problem :

https://leetcode.com/problems/remove-nth-node-from-end-of-list


My Solution :

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
first = second = dummy = ListNode(0)
dummy.next = head
for _ in range(n):
first = first.next
while first and first.next:
first = first.next
second = second.next
second.next = second.next.next
return dummy.next


Comment :

Cracking the Coding Interview 책에서 봤던 문제라 별 고민 없이 two pointer 전략으로 접근하였다. Linked List는 항상 Edge Case 때문에 고생하는데 dummy head를 활용하는게 일종의 트릭이 될 수 있다.