2487. Remove Nodes From Linked List

2487. Remove Nodes From Linked List #

题目 #

给定链表头节点head,对于链表中的每个节点node,如果其右侧存在一个具有严格更大值的节点,则移除node

返回修改后链表的头节点head

思路 #

代码 #

反转&移除 #

public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution{
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
    public ListNode removeNodes(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode sentinel = new ListNode(-1, head);
        ListNode tail = reverseList(sentinel), ptr = tail;
        int maxVal = ptr.val;
        while (ptr.next != sentinel) {
            if (ptr.next.val < maxVal) ptr.next = ptr.next.next;
            else {
                maxVal = ptr.next.val;
                ptr = ptr.next;
            }
        }
        reverseList(tail);
        return sentinel.next;
    }
}

递归 #

public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
    public ListNode removeNodes(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode ptr = removeNodes(head.next);
        if (head.val < ptr.val) return ptr;
        else {
            head.next = ptr;
            return head;
        }
    }
}