首页 > 其他 > 详细

leetcode19-单链表

时间:2021-09-11 15:53:24      阅读:23      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 技术分享图片

 

 解题思路:

首先构造一个节点slownode,它的next引用给定链表的头结点的地址。

之后把slownode赋值给fastnode。

将fastnode往前移动n步,

再将fastnode和slownode一起往前移动,直到fastnode移到最后一个位置。

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution(object):
    def removeNthFromEnd(self, head, n):
        if not head:
            return head
        slownode=ListNode(None)
        slownode.next=head
        fastnode=slownode
        for i in range(n):
            fastnode=fastnode.next
        while fastnode.next!=None:
            slownode=slownode.next
            fastnode=fastnode.next
        if slownode.next==head:
            head=head.next
        else:
            slownode.next=slownode.next.next
        return head

代码详解:

首先head=[1,2,3,4,5]

head这个变量引用的是链表头结点的地址。

leetcode19-单链表

原文:https://www.cnblogs.com/hugrice/p/15252697.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!