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

79 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第28天,点击查看活动详情

indexOf(data)

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

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

image.png

编码

  • 定义indexOf方法,参数是data
  • current变量从头部开始(指向头部),下表也从0开始
  • 当current不为空(为空就是一直找到了,tail后的元素null),如果current的data和我们传入的data相等,返回index索引
  • 如果不相等,current向下寻找,index自增。
  • 最后,如果找不到返回-1。
 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
          }

测试一下

// 测试
      var list = new TwoWayLinkList();
      list.append('abc');
      list.append('bce');
      list.append('ghg');
      console.log(list.indexOf('bce'));   

image.png

update(position,element)

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

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

编码

  • 两个参数:position和新的数据
  • 做下越界判断,position不能为负数,以及不能超过长度
  • 寻找节点:只要我们记录当前current指向的索引index的值小于postion,就将current = current.next也就是向下寻找。index++<position在与position比较的同时,还在递增。
  • 最后将找到的节点的data赋值为新的newData,并返回true。
 // 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
        }

测试一下

  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