---
description: LeetCode 19 (one pass)
---

# Remove Nth Node From End of List

```python
# 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
        """
        
        """
        dummy node 在解決 linkedlist 的問題時可以節省很多麻煩
        另外面試時可以問 is n valid, 如果它大於鏈結長度, one pass 解法會沒戲唱
        dummy -> 1 -> 2 -> 3 -> 4 -> 5
                           t
                                     r
        """
        dummy = ListNode(0)
        turtle = rabbit = dummy 
        dummy.next = head
        for _ in range(n):
            rabbit = rabbit.next
        
        while rabbit.next:
        # while rabbit and rabbit.next
            turtle = turtle.next
            rabbit = rabbit.next
        
        turtle.next = turtle.next.next
        
        return dummy.next
```
