js 算法3

又看到一個算法
題目:鏈表中倒數第k個結點
這個題目看到 又是一個鏈表 在編輯器上調試了兩種方法來看一下node

  • 思路 將鏈表從頭至尾遍歷一遍 沒遍歷到一個節點爲計數器加1 第一遍循環完 知道了節點個數 而後再遍歷一遍找到倒數第k個節點
function Node (value) {  //構造函數 Node
      this.value = value
      this.next = null
  }
  Node.prototype.setNext= function(node) {
      this.next = node
      return node
  }  
  var head = new Node(1)
  console.log(head)  //Node {value: 1, next: null} 建立了1節點  接下了建立2 3 4
  var two = new Node(2)
  var three = new Node(3)
  var four = new Node(4)
  head.setNext(two).setNext(three).setNext(four)
  console.log("節點"head)  //Node {value: 1, next: {。。。。}} 這裏建立了一個單鏈表  1234
  console.log(FindNode(head, 2)) //這裏找到倒數第2個k節點
  function FindNode(head, k){
    if (head == null || k <= 0) {
      return null
    }
    //按照思路說的來循環下 算出節點數
    var nodenum = 0
    var cursor = head
    while(nodenum !=null){
        nodenum++
        cursor = cursor.next
    }
    //上面這一循環 找出節點數 nodenum 4個節點  

    // 這裏找倒數第k個 就是正數第 nodenum-k+1個節點  
    var index = 1 //用來從第一個開始  跟nodenum-k+1 對比
    var cursor2 = head
    while(index !=nodenum-k+1) {  //這個循環來 從第一個 1到nodenum-k+1 來循環  找到就出來  後面就是節點就是倒數k個節點
        index++    
        cursor2 = sursor2.next
    }
    return cursor2
  }複製代碼

上面要循環兩遍才能找到 節點 不是特別高效
看到網上一個好的解法 下面調試下 算法

  • 思路 由於單向鏈表不能回退 因此就定義兩個指針 (1) 第一個指針從表頭開始走k-1 第二個指針不動 (2) 從第k步開始 第二個指針也開始從鏈表頭開始遍歷

function Node (value) {  //構造函數 Node
      this.value = value
      this.next = null
  }
  Node.prototype.setNext= function(node) {
      this.next = node
      return node
  }  
  var head = new Node(1)
  console.log(head)  //Node {value: 1, next: null} 建立了1節點  接下了建立2 3 4
  var two = new Node(2)
  var three = new Node(3)
  var four = new Node(4)
  head.setNext(two).setNext(three).setNext(four)
  console.log("節點"head)  //Node {value: 1, next: {。。。。}} 這裏建立了一個單鏈表  1234
  console.log(FindNode(head, 2)) //這裏找到倒數第2個k節點

  function FindNode(head, 2) {
    if (k < 0 || !head) {
      return null
    }
    var cursor = head   //第一個指針
    var cursor2 = head  //第二個指針
    for (var i=0; i<k-1; i++) {
        if(cursor.next == null) {  //這裏判斷記得別給掉了  有可能這個只有一個節點下個節點就是null 
            return null
        } else {
            cursor = cursor.next   
        }
    }
    //上面第一個指針cursor 如今指在了k-1那個節點上   
    //下面循環將第一個 第二個 向後走 
    while(cursor.next ) {
        cursor = cursor.next  //向後走 循環次數的步數
        cursor2 = cursor2.next
    }
    return cursor2
  }複製代碼

上面這種要比第一種效率 高點 由於只循環了一遍bash

兩種方法 本地已經調通 有好的方法能夠補充編輯器

相關文章
相關標籤/搜索