DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

LeetCode "Remove Nth Node From End of List"

I solved, but this could be shorter☹️

Remove Nth Node From End of List

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

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if n == 0:
            return None
        if n == 1 and head.next is None:
            return None

        i = 1
        before = None
        target = head
        node = head
        while node:
            if n < i:
                before = target
                target = target.next
            i += 1
            node = node.next

        if before is None:
            return head.next

        before.next = target.next    
        return head
Enter fullscreen mode Exit fullscreen mode

Top comments (0)