# LC 19. Remove Nth Node From End of List ### [Problem link](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) ###### tags: `leedcode` `medium` `python` `c++` `Linked List` Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head. **Example 1:** <img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" style="width: 542px; height: 222px;" /> ``` Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] ``` **Example 2:** ``` Input: head = [1], n = 1 Output: [] ``` **Example 3:** ``` Input: head = [1,2], n = 1 Output: [1] ``` **Constraints:** - The number of nodes in the list is <code>sz</code>. - <code>1 <= sz <= 30</code> - <code>0 <= Node.val <= 100</code> - <code>1 <= n <= sz</code> **Follow up:** Could you do this in one pass? ## Solution 1 - Linked List(Follow up) #### Python ```python= # 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]: dummy = ListNode(next = head) fast = slow = dummy for _ in range(n): fast = fast.next while fast.next: fast = fast.next slow = slow.next slow.next = slow.next.next return dummy.next ``` #### C++ ```cpp= /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *dummy = new ListNode(0, head); ListNode *fast = dummy; for (int i = 0; i < n; i++) { fast = fast->next; } ListNode *slow = dummy; while (fast->next != nullptr) { fast = fast->next; slow = slow->next; } slow->next = slow->next->next; return dummy->next; } }; ``` >### Complexity >n = The number of nodes in the list. >| | Time Complexity | Space Complexity | >| ------------------- | --------------- | ---------------- | >| Solution 1(C++) | O(n) | O(1) | >| Solution 1(Python) | O(n) | O(n) | ## Note 建議紙筆畫一畫.