LC.P2487[从链表中移除节点]

方法一:单调栈

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
/**
* Definition for singly-linked list.
* 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) {
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;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* 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) return null;
head.next = removeNodes(head.next);
if (head.next != null && head.val < head.next.val) {
return head.next;
} else {
return head;
}
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$