JavaScript 单链表的简单实现以及操作(JavaScript 数据结构-链表)

链表用来存储有序的元素集合,与数组不同,链表中的元素并非保存在连续的存储空间内,每个元素由一个存储元素本身的节点和一个指向下一个元素的指针构成。当要移动或删除元素时,只需要修改相应元素上的指针就可以了。

   //构建Node
   function Node(element) {
    this.element = element;
    this.next = null;
   }
   
   //构建LinkList
   function LinkList() {
    this.head = new Node("header");
    this.findNode = findNode;
    this.findNodeEle = findNodeEle;
    this.insert = insert;
    this.removePos = removePos;
    this.removeELe = removeEle;
    this.printAll = printAll;
    this.addNode = addNode;
   }
   
   //增加节点
   function addNode(ele) {
    let newNode = new Node(ele);
    let curNode = this.head;
    while(curNode.next != null) {
     curNode = curNode.next;
    }
    curNode.next = newNode;
    newNode.next = null;
   }
   
   //根据位置查找结点
   function findNode(position) {
    if (position < 0) {
     return null;
    }
    let curNode = this.head;
    for (let i = 0; i < position; i++) {
     curNode = curNode.next;
    }
    return curNode;
   }
   
   //根据元素查找结点
   function findNodeEle(ele) {
    let curNode = this.head;
    while (curNode.element != ele && curNode.next) {
     curNode = curNode.next;
    }
    if (curNode.element == ele) {
     return curNode;
    }
    return -1;
   }
   
   //插入节点
   function insert(position, ele) {
    if (position < 0) {
     return "插入位置不能小于0";
    }
    let newNode = new Node(ele);
    let curNode = this.findNode(position);
    newNode.next = curNode.next;
    curNode.next = newNode;
   }
   
   //根据位置删除节点
   function removePos(position) {
    if (position < 0) {
     return "删除节点位置不能小于0";
    }
    let curNode = this.head;
    for (let i = 0; i < position; i++) {
     curNode = curNode.next;
    }
    curNode.next = curNode.next.next;
   }
   
   //根据元素删除节点
   function removeEle(ele) {
    let curNode = this.head;
    while (curNode.next.element != ele) {
     curNode = curNode.next;
    }
    curNode.next = curNode.next.next;
   }
   
   //输出节点
   function printAll() {
    let curNode = this.head;
    while(curNode.next != null) {
     console.log(curNode.next.element);
     curNode = curNode.next;
    }
   }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值