标签:经典的 rem linked ext 题目 lazy inf list nod
题目:
思路:一道经典的快慢指针问题,快指针先走n步,然后一起走,快指针走到最后一个节点,慢指针就到了要被删除的节点的前一个节点。
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: node = ListNode(0) node.next = head #定义头节点 fast = node slow = node for i in range(n): fast = fast.next #快节点先走n步 while(fast.next!=None):#直到快节点走到最后一个,慢节点直接指向她的后继节点的后继节点 fast = fast.next slow = slow.next slow.next = slow.next.next return node.next
标签:经典的 rem linked ext 题目 lazy inf list nod
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/14791068.html