LeetCode 分类刷题:2487. 从链表中移除节点

题目

给你一个链表的头节点 head 。

移除每个右侧有一个更大数值的节点。

返回修改后链表的头节点 head 

解析

我的思路过程:

    // 记录右侧最大值
    // 大于当前值则删除当前节点

    // 反转链表
    // 记录遍历到该节点时的最大值(可以只用一个值)
    // 如果不是本身,则右侧有最大值,删掉该节点(头节点肯定不会被删)

    // 如果下个节点的值小于当前节点,则删除下一个节点(循环删除)
    // 再反转回来

答案

/**
 * 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}
 */
function reverseList(head) {
    let pre = null;
    let cur = head;
    while(cur) {
        const nxt = cur.next;
        cur.next = pre;
        pre = cur;
        cur = nxt;
    }
    return pre;
}
var removeNodes = function(head) {
    const head2 = reverseList(head);
    let cur = head2;
    while(cur.next) {
        if(cur.val > cur.next.val) {
            cur.next = cur.next.next;
        } else {
            cur = cur.next;
        }
    }
    return reverseList(head2);
};

复杂度分析

时间复杂度:O(n)

空间复杂度:O(1)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值