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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay