雙向鏈表

雙向鏈表和普通鏈表的區(qū)別在于,雙向鏈表鏈接是雙向的,一個(gè)鏈向上一個(gè)元素,一個(gè)鏈向下一個(gè)元素。
所以一個(gè)元素應(yīng)該是:

node = function(element){
    this.element = element
    this.prev = null// 指向上一個(gè)
    this.next = null// 指向下一個(gè)
}

同時(shí)不僅包括head,還應(yīng)該有tail,記錄最后一個(gè)元素,

let head = null
let tail = null
let length = 0

2 方法實(shí)現(xiàn)

2.1在任意位置插入新元素和移除新元素

function DoublyLinkedList(){
  let Node = function(element){
    this.element = element
    this.prev = null
    this.next = null
  }
  let head = null
  let tail = null
  let length = 0
  this.insert = function (position,element){
    if(position>=0&&position<=length){// 考慮臨界情況
      let node = new Node(element),
      current = head,
      prev,
      index = 0    
      if(position==0){
        if(!head){
          head = node
          tail = node
        }else{
          node.next = current //  node變成了head
          current.prev = node //  之前的head變成了node的下項(xiàng) 
          head = node // 賦值
        }
      }else if(position==length){
        current = tail //保存tail的值
        current.next = node //tail的next指向node
        node.prev = current //node的prev指向之前的tail
        tail = node  //將最后一個(gè)值保存為tail
      }else{
        while(index<position){
          prev = current //保存現(xiàn)任值
          current = current.next// 現(xiàn)任變前任,后任繼位
          index++ //索引值增加
        }
        prev.next = node
        node.prev = prev
        node.next = current
        current.prev = node
        
      }
        length++
        return node
    }else{
      return null
    }
  }
//在任意位置移除元素
  this.remove = function(position){
      if(position>=0&&position<=length-1){
        let current = head,index =0,prev
        if(position==0){
        current = current.next
        head = current
        // 還需要改變prev 和 tail
          if(length ===1){
            tail = null
          }else{
            head.prev = null
          }
        }else if(position ==length-1){
        current = tail
        tail = current.prev
        tail.next =null
        }else{
          while(index<position){
            prev = current
            current = current.next
            index++
          }
          prev.next = current.next
          current.next.prev =prev
          
          
        }
        length --
          return current
      }else{
        return null
      }
}
//打印head
  this.print = function(){
    console.log(head)
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容