删除链表的倒数第N个节点(JS版本)

栏目: JavaScript · 发布时间: 5年前

内容简介:先实现一个单向链表
删除链表的倒数第N个节点(JS版本)

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
    • 之后 startend 共同向前移动,此时二者的距离为 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节点,也就是删除了
复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Rails Cookbook

Rails Cookbook

奥西尼 / 江苏东南大学 / 2007-6 / 68.00元

Rails是业界领先的新一代Web 2.0应用程序开发框架,而这本《Rails Cookbook》里充满了为了让你成为Rails开发专家而准备的各种解决方案。讨论范围覆盖了从基本概念,如安装Rails及设置开发环境,到最新的各种技巧,如开发符合REST协议规范的Web服务等。 Rails可提供更轻量级的代码、更丰富的功能和更快捷的量身定制过程,由此带来了一场Web开发革命。《Rails Co......一起来看看 《Rails Cookbook》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试