zoukankan      html  css  js  c++  java
  • 删除链表倒数第n个节点(19)

    法一:
    # 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: # 设置虚拟指针的目的是防止删除第一个节点 dum = ListNode(0) dum.next = head cur = head pre = dum # 先走n步 for _ in range(n): cur = cur.next # 再走剩余的步,最后pre指向的就是要删除节点的前面一个节点 while cur: cur = cur.next pre = pre.next #删除这个节点 pre.next = pre.next.next return dum.next

    法二:

    class Solution:
      def removeNthFromEnd(self, head, n):
        global i
        if head is None:
          i=0
          return None
        head.next = self.removeNthFromEnd(head.next,n)
        i+=1
        return head.next if i==n else head

  • 相关阅读:
    Android Time类 奇葩的设定
    zjut1698Coins
    zjut1689联盟
    zju1024Calendar Game
    hdu2863Top Shooter
    hdu3974Assign the task
    hdu1150Machine Schedule
    线段树无止尽版
    zjut1684AirCraft
    hdu3926Hand in Hand
  • 原文地址:https://www.cnblogs.com/miaoweiye/p/13518761.html
Copyright © 2011-2022 走看看