题目描述:
代码可以这么理解:removeNodes 函数的作用就是将 head 节点的后续节点置为连续不增,
因此可以递归调用该函数。
假设 head 节点的后续节点都已经连续不增了,那么就只需要考虑
head 和它上一个节点的关系了。
c++代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNodes(ListNode* head) {
if(head == nullptr){ //递归出口
return head;
}
head->next = removeNodes(head->next); //让 head->next 后面的节点连续递减
if(head->next == nullptr){
return head;
}
if(head->val < head->next->val){ //判断 head 和 head->next 的大小关系
return head->next ;
}
else{
return head;
}
}
};