DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

1 3

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay