Quick actions

cmd+k|ctrl+k

Navigation

Languages

Remove Nth to Last Node | Python

Snippet info

Language

Python

Visibility

public

Author

ralletsfix

Created

2022-05-12T15:09:38.755025Z

Updated

2022-05-12T15:09:38.755025Z

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

    def __str__(self):
        return str(self.value)
   
class LinkedList:
    def __init__(self, *items):
        self.head = None
        self.tail = None
        
        self.add(*items)
   
    def add(self, *items):
        for item in items:
            self.addAtEnd(item)
       
    def addAtEnd(self, value):
        if not self.head:
            self.head = self.tail = Node(value)
        else:
            curr = self.head
            while curr.next:
                curr = curr.next
            curr.next = Node(value)
            self.tail = curr.next
    
    def elems(self):
        curr = self.head
        count = 0
        while curr:
            count += 1
            curr = curr.next
        return count
        
    def __str__(self):
        curr = self.head
        res = []
        while curr:
            res.append(str(curr.value))
            curr = curr.next
        return "->".join(res)
        
def removeNthToLastNode(lst: LinkedList, n: int):
    numOfItems = lst.elems()
    if n > numOfItems:
        raise Exception(f"Index out of Range. Expected: 1..{numOfItems}. Got: {n}")
    
    prev = None
    curr = lst.head
    while curr and numOfItems != n:
        prev = curr
        curr = curr.next
        numOfItems -= 1

    if prev and curr:
        prev.next = curr.next
    elif curr and numOfItems == n:
        lst.head = lst.head.next

    return lst
    
tests = [
    ([1, 2, 3], 1, '1->2'),
    ([1, 2, 3], 2, '1->3'),
    ([1, 2, 3], 3, '2->3'),
    ([4, 4, 7, 1, 5, 6], 0, '4->4->7->1->5->6'),
    ([4, 4, 7, 1, 5, 6], 1, '4->4->7->1->5'),
    ([4, 4, 7, 1, 5, 6], 6, '4->7->1->5->6'),
    ([4, 4, 7, 1, 5, 6], 2, '4->4->7->1->6'),
    ([4, 4, 7, 1, 5, 6], 5, '4->7->1->5->6'),
]

for i, (a, n, expected) in enumerate(tests):
    l = LinkedList(*a)
    got = str(removeNthToLastNode(l, n))
    if got == expected:
        print(f"PASS")
    else:
        print(f"FAIL: expected '{expected}', got '{got}'")
INFO