题目描述
- 给你一个链表的头节点
head
。 - 移除每个右侧有一个更大数值的节点。
- 返回修改后链表的头节点
head
。
示例 1:
输入:head = [5,2,13,3,8] 输出:[13,8] 解释:需要移除的节点是 5 ,2 和 3 。 - 节点 13 在节点 5 右侧。 - 节点 13 在节点 2 右侧。 - 节点 8 在节点 3 右侧。
示例 2:
输入:head = [1,1,1,1] 输出:[1,1,1,1] 解释:每个节点的值都是 1 ,所以没有需要移除的节点。
提示:
- 给定列表中的节点数目在范围
[1, 105]
内 1 <= Node.val <= 105
解题思路:
通过递归的方式,遍历链表,如链表的下一个值比当前值大,则移除当前节点.
/**
*以示例1为例:
*递归在链表的head.next=null时停止,此时head.val=8,返回head(val=8 next=null),
*执行下一次递归,此时head=3,head.next.val=8,3<8,返回head.next(val=8 next=null),
*执行下一次递归,此时head=13,head.next.val=8,13>8,返回head(val=13,next=(val=8,next=null)),
*执行下一次递归,此时head=2,head.next.val=13,2<13,返回head(val=13,next=(val=8,next=null)),
*执行最末次递归,此时head=5,head.next.val=13,5<13,返回head(val=13,next=(val=8,next=null)),
*最后的值为[13,8].
*/
题解:
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;
}
}
}