File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * public class ListNode {
4
+ * int val;
5
+ * ListNode next;
6
+ * ListNode() {}
7
+ * ListNode(int val) { this.val = val; }
8
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9
+ * }
10
+ */
11
+ class Solution {
12
+ public ListNode removeNodes (ListNode head ) {
13
+ ListNode revNode = reverse (head );
14
+ ListNode curr = revNode ;
15
+ ListNode prev = null ;
16
+ int maxValue = Integer .MIN_VALUE ;
17
+ while (curr != null ) {
18
+ if (curr .val < maxValue ) {
19
+ prev .next = curr .next ;
20
+ } else {
21
+ prev = curr ;
22
+ maxValue = Math .max (curr .val , maxValue );
23
+ }
24
+ curr = curr .next ;
25
+ }
26
+ return reverse (revNode );
27
+ }
28
+
29
+ private ListNode reverse (ListNode node ) {
30
+ ListNode curr = node ;
31
+ ListNode prev = null ;
32
+ while (curr != null ) {
33
+ ListNode next = curr .next ;
34
+ curr .next = prev ;
35
+ prev = curr ;
36
+ curr = next ;
37
+ }
38
+ return prev ;
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments