题目
给你一个链表的头节点 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)


260

被折叠的 条评论
为什么被折叠?



