删除链表的倒数第N个节点(JS版本)
栏目: JavaScript · 发布时间: 6年前
内容简介:先实现一个单向链表
2. 思路:
先实现一个单向链表
// 节点
function Node(value) {
this.value = value; // 当前节点的元素
this.next = null; // 下一个节点的链接
}
// 查找给定节点位置
function find(item) {
let curNode = this.head;
while (curNode.value !== item) {
curNode = curNode.next;
}
return curNode;
}
// 插入节点
function insert(value, preValue) {
const newValue = new Node(value);
const curNode = this.find(preValue);
newValue.next = curNode.next;
curNode.next = newValue;
}
function SList() {
this.head = new Node('head'); // 头节点
this.find = find;
this.insert = insert;
}
const list = new SList();
list.insert('1', 'head');
list.insert('2', '1');
list.insert('3', '2');
list.insert('4', '3');
list.insert('5', '4');
console.log(list);
复制代码
3. 单项链表
head -> 1 -> 2 -> 3 -> 4 -> 5 复制代码
4. 代码实现题目要求
- 思路
- 让前面的指针先移动n步,之后前后指针共同移动直到前面的指针到尾部为止
- 前指针为
start,后指针为end,二者都等于head -
start先向前移动n步 - 之后
start和end共同向前移动,此时二者的距离为n,当start到尾部时,end的位置恰好为倒数第n个节点 - 因为要删除该节点,所以要移动到该节点的前一个才能删除,所以循环结束条件为
start.next != null - 删除后返回
head.next,为什么不直接返回head呢,因为head有可能是被删掉的点 - 时间复杂度:
O(n)
const removeNthFromEnd = function (head, n) {
if (head === null || n === 0) return head;
let start = head;
let end = head;
while (n > 0) {
start = start.next;
n--;
}
// 如果start为空,删除首部head
if (start === null) {
return head.next;
}
while (start.next != null) {
start = start.next;
end = end.next;
}
// 删除
end.next = end.next.next;
return head;
};
复制代码
5. 执行代码
const res = removeNthFromEnd(list.head, 2); console.log(res); 复制代码
6. 执行过程
end = 0 1 2 3 start = 2 3 4 5 找到3节点,end.next = end.next.next 替换4节点,也就是删除了 复制代码
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- [leetcode-JavaScript]---19.删除链表的倒数第N个节点
- xml创建节点(根节点、子节点)
- Vultr VPS 节点选择方法 | 各节点延迟一览
- 1.19 JQuery2:节点插入与节点选取
- POC分布式节点算法机制下的超级节点计划
- tikv节点下线缩容后改造成tidb节点记录
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
谁说商业直觉是天生的
[美] 戴夫·帕特奈克 (Dev Patnaik)、[美] 彼得·莫特森 (Peter Mortensen) / 马慧 / 万卷出版公司 / 2010-07 / 36.00
《Wired to Care》是帕特奈克集近年来在创新顾问公司 Jump Associates 实务经验,与史丹佛大学教学经验之大成,虽然《Wired to Care》定位为一本用设计创新方法谈企业管理的书,但本书,活像是一本近代的设计史,从以销售为设计目标的Raymond Loewy谈起,到以人为设计中心的OXO GOOD GRIPSSwivelPeeler削皮刀。由此作者向我们揭示了企业如何运......一起来看看 《谁说商业直觉是天生的》 这本书的介绍吧!