leetcode python3 删除链表的倒数第N个节点

代码思路:采用双指针,快指针先走n次,接下来快慢指针同时走,直到快指针走完时,慢指针所在位置即为需要删除的节点

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        slow=head
        fast=head
        while n>0:
            fast=fast.next
            n-=1
        if fast:
            while fast.next:
                fast=fast.next
                slow=slow.next
            slow.next=slow.next.next
            return head
        else:
            return head.next
发布了30 篇原创文章 · 获赞 0 · 访问量 319

猜你喜欢

转载自blog.csdn.net/m0_37656366/article/details/104789687
今日推荐