---
# System prepended metadata

title: 2487. Remove Nodes From Linked List
tags: [Leetcode, Linked List, Medium]

---

# 2487. Remove Nodes From Linked List
###### tags: `Leetcode` `Medium` `Linked List`
Link: https://leetcode.com/problems/remove-nodes-from-linked-list/description/
## 思路
### Reverse Linked List
先reverse linked list
然后从头扫一遍 记录前面出现的最大值 任何一个node如果比前面出现的最大值小 那么就删掉这个node
然后再reverse回来
### Recursion
参考[这里](https://leetcode.com/problems/remove-nodes-from-linked-list/solutions/2852139/java-c-python-3-line-recursion-solution/)
## Code
### Reverse Linked List
```java=
class Solution {
    public ListNode removeNodes(ListNode head) {
        head = reverseLinkedList(head);
        ListNode prev = head, curr = head.next;
        int maxValue = head.val;
        while(curr!=null){
            if(curr.val<maxValue) prev.next = curr.next;
            else{
                maxValue = Math.max(maxValue, curr.val);
                prev = prev.next;
            }
            curr = curr.next;
        }
        return reverseLinkedList(head);
    }
    public ListNode reverseLinkedList(ListNode head){
        ListNode curr = head;
        ListNode prev = null, next = null;
        while(curr!=null){
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
}
```
### Recursion
```java=
class Solution {
    public ListNode removeNodes(ListNode head) {
        if(head==null) return null;
        head.next = removeNodes(head.next);
        return head.next!=null && head.next.val>head.val ? head.next : head;
    }
}
```