显然只要从后往前遍历链表,设 t 为当前的最大值,只要在遍历过程中比 t 小的节点都删除,大于等于 t 的则更新 t 为新的节点
通过递归回溯的方法可以很简单地实现从后往前遍历链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:if head.next == None:t = headelse:t = self.removeNodes(head.next)if t.val <= head.val:head.next = treturn headreturn t