class Solution {
public ListNode removeNodes(ListNode head) {
head = reverse(head);
ListNode cur = head;
int max = cur.val;
while (cur.next != null) {
max = Math.max(max, cur.val);
if (max > cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return reverse(head);
}
private ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}