码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-05-01 10:23:41      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:位置   +=   info   height   col   mamicode   res   init   self   

技术图片

两次遍历

思路:

先遍历一次得到数组长度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个节点

标签:位置   +=   info   height   col   mamicode   res   init   self   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!