法一:
# 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