前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >双向链表[js实现] 【5】

双向链表[js实现] 【5】

作者头像
用户4793865
发布2023-01-12 13:13:17
2790
发布2023-01-12 13:13:17
举报
文章被收录于专栏:前端小菜鸡yym前端小菜鸡yym

indexOf(data)

用途: 根据data找到其位置。

思路: 定义current不断向下查找,用index记录索引值。对比current的data和我们传入的参数data,如果相等,把index返回。

image.png
image.png

编码

  • 定义indexOf方法,参数是data
  • current变量从头部开始(指向头部),下表也从0开始
  • 当current不为空(为空就是一直找到了,tail后的元素null),如果current的data和我们传入的data相等,返回index索引
  • 如果不相等,current向下寻找,index自增。
  • 最后,如果找不到返回-1。
代码语言:javascript
复制
 TwoWayLinkList.prototype.indexOf = function(data){
              // 1.定义变量
              var current = this.head
              var index = 0
              // 2.查找和data相同的节点。
              while(current){
                  if(current.data==data){
                      return index
                  }else{
                      current=current.next;
                      index+=1
                  }
              }
              return -1
          }
复制代码

测试一下

代码语言:javascript
复制
// 测试
      var list = new TwoWayLinkList();
      list.append('abc');
      list.append('bce');
      list.append('ghg');
      console.log(list.indexOf('bce'));   

image.png
image.png

update(position,element)

用途: 更改指定位置的元素为传进来的元素。

思路: 定义current变量,向下寻找,找到节点后那,把这个节点的data更改为我们传进来的。

编码

  • 两个参数:position和新的数据
  • 做下越界判断,position不能为负数,以及不能超过长度
  • 寻找节点:只要我们记录当前current指向的索引index的值小于postion,就将current = current.next也就是向下寻找。index++<position在与position比较的同时,还在递增。
  • 最后将找到的节点的data赋值为新的newData,并返回true。
代码语言:javascript
复制
 // update
        TwoWayLinkList.prototype.update = function (position,newData){
            // 越界判断
            if(position<0 || position>=this.length) return false
            // 寻找正确节点
            var current = this.head
            var index = 0
            while(index++<position){
                current = current.next
            } 
            // 修改找到的节点信息
            current.data = newData
            return true
        }
复制代码

测试一下

代码语言:javascript
复制
  var list = new TwoWayLinkList();
      list.append('abc');
      list.append('bce');
      list.append('ghg');
      console.log(list.update(0,'sdsds'));
      console.log(list.update(2,'ss'));
      console.log(list.toString())

如下,list本来是 'abc bce ghg'

image.png
image.png
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • indexOf(data)
    • 编码
      • 测试一下
      • update(position,element)
        • 编码
          • 测试一下
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档