Problem: 2487. 从链表中移除节点
思路
这个问题要求我们移除链表中每个右侧有一个更大数值的节点。解决方案采用递归的方法,从链表的末尾开始向前处理,每次查看相邻两个节点的大小关系,将不符合要求的节点移除。
解题方法
- 递归基础:如果当前节点为空,直接返回它。这是递归的终止条件。
- 递归处理:对当前节点的下一个节点调用递归函数,以处理链表的剩余部分。
- 节点比较:比较当前节点和它的下一个节点的值。如果当前节点的值小于下一个节点的值,意味着当前节点应该被移除。
- 返回结果:根据比较结果,返回适当的节点作为新的链表头。
复杂度
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
Code
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var removeNodes = function(head) {
// 递归终止条件
if (!head) {
return head
}
// 递归处理链表的剩余部分
head.next = removeNodes(head.next)
// 比较当前节点与下一个节点的值
if (head.next !== null && head.val < head.next.val) {
return head.next // 移除当前节点
} else {
return head // 保留当前节点
}
};
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNodes(ListNode head) {
// 递归终止条件
if (head == null) {
return head;
}
// 递归处理链表的剩余部分
head.next = removeNodes(head.next);
// 比较当前节点与下一个节点的值
if (head.next != null && head.val < head.next.val) {
return head.next; // 移除当前节点
} else {
return head; // 保留当前节点
}
}
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 递归终止条件
if not head:
return head
# 递归处理链表的剩余部分
head.next = self.removeNodes(head.next)
# 比较当前节点与下一个节点的值
if head.next and head.val < head.next.val:
return head.next # 移除当前节点
else:
return head # 保留当前节点