|
| 1 | +# https://neetcode.io/problems/remove-node-from-end-of-linked-list |
| 2 | + |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import unittest |
| 6 | + |
| 7 | +class ListNode: |
| 8 | + def __init__(self, val=0, next=None): |
| 9 | + self.val = val |
| 10 | + self.next = next |
| 11 | + |
| 12 | +def remove_nth_from_end(head: Optional[ListNode], n: int) -> Optional[ListNode]: |
| 13 | + def get_length(head: Optional[ListNode]): |
| 14 | + length: int = 0 |
| 15 | + |
| 16 | + current: ListNode = head |
| 17 | + |
| 18 | + while current: |
| 19 | + length += 1 |
| 20 | + |
| 21 | + current = current.next |
| 22 | + |
| 23 | + return length |
| 24 | + |
| 25 | + length: int = get_length(head) |
| 26 | + |
| 27 | + # When the node to remove is the `head` itself |
| 28 | + if length == n: |
| 29 | + return head.next |
| 30 | + |
| 31 | + target_index: int = length - n |
| 32 | + |
| 33 | + current: ListNode = head |
| 34 | + previous: ListNode = ListNode() |
| 35 | + count: int = 0 |
| 36 | + |
| 37 | + while current: |
| 38 | + if count == target_index: |
| 39 | + previous.next = current.next |
| 40 | + break |
| 41 | + |
| 42 | + previous = current |
| 43 | + current = current.next |
| 44 | + |
| 45 | + count += 1 |
| 46 | + |
| 47 | + return head |
| 48 | + |
| 49 | +class Test(unittest.TestCase): |
| 50 | + def test_example(self): |
| 51 | + # Create the linked list 1 -> 2 -> 3 -> 4 -> 5 |
| 52 | + head = ListNode(1) |
| 53 | + head.next = ListNode(2) |
| 54 | + head.next.next = ListNode(3) |
| 55 | + head.next.next.next = ListNode(4) |
| 56 | + head.next.next.next.next = ListNode(5) |
| 57 | + |
| 58 | + # Remove the 2nd node from the end, which is '4' |
| 59 | + new_head = remove_nth_from_end(head, 2) |
| 60 | + |
| 61 | + # Verify the new linked list is 1 -> 2 -> 3 -> 5 |
| 62 | + self.assertEqual(new_head.val, 1) |
| 63 | + self.assertEqual(new_head.next.val, 2) |
| 64 | + self.assertEqual(new_head.next.next.val, 3) |
| 65 | + self.assertEqual(new_head.next.next.next.val, 5) |
| 66 | + self.assertIsNone(new_head.next.next.next.next) |
0 commit comments