1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
class Solution { public ListNode removeNodes(ListNode head) { ListNode dummy = new ListNode(0, head); Deque<ListNode> stack = new ArrayDeque<>(); for (ListNode cur = head; cur != null; cur = cur.next) { while (!stack.isEmpty() && stack.peek().val < cur.val) { stack.pop(); } if (stack.isEmpty()) { dummy.next = cur; } else { stack.peek().next = cur; } stack.push(cur); } return dummy.next; } }
|