首页 > 其他 > 详细

leetcode 每日一题 19. 删除链表的倒数第N个节点

时间:2020-05-01 11:35:10      阅读:50      评论:0      收藏:0      [点我收藏+]

技术分享图片

两次遍历

思路:

先遍历一次得到数组长度length,第二次遍历找到位置在length-n的节点p,让p.next=p.next.next即可

代码:

 

# 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:
        result = ListNode(0)
        result.next = head
        length = 0
        first = head
        while first:
            first = first.next
            length +=1
        length -= n
        first = head 
        for i in range(length-1):
            first = first.next
        first.next = first.next.next
        return result.next

 

快慢指针

两个指针距离为n,同时移动,只需要一次遍历,当快指针到终点,慢指针对应位置,做删除节点操作。

代码:

# 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:
        result = ListNode(0)
        result.next,fast,slow = head,result,result
        for i in range(n):
            fast = fast.next
        while fast:
            fast = fast.next
            slow = slow.next if fast else slow
        slow.next = slow.next.next
        return result.next

 

leetcode 每日一题 19. 删除链表的倒数第N个节点

原文:https://www.cnblogs.com/nilhxzcode/p/12812591.html

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