首页 > 技术文章 > 链表操作

finghi 2021-09-07 21:11 原文

链表结构

function linkedList(){
      function Node(data){
        this.data=data
        this.next=null
      }
      this.length=0
      this.head=null
}

链表添加元素方法

linkedList.prototype.append=function(data){
        var newNode =new Node(data)
        if(this.length==0){
          this.head=newNode
        }else{
          var current=this.head
          while(current.next){
            current=current.next
          }
          current.next=newNode
        }
        this.length+=1
}

链表打印字符串方法

linkedList.prototype.toString = function(){        
        var current=this.head
        var mess = " "
        while(current){           
            mess+=current.data + ' '
            current=current.next
    }
        return mess
}

在链表的指定位置插入元素

linkedList.prototype.insert = function (index, data) {
        if (index < 0 || index > this.length) return false //判断如果index小于或大于长度就返回false
        var newNode = new Node(data)
        if (index == 0) {
          newNode.next = this.head
          this.head = newNode
        } else {
          var i = 0;
          var current = this.head;
          var pre = null;
          while (i++ < index) {
            pre=current
            current=current.next
          }
          pre.next=newNode
          newNode.next=current
        }
        this.length+=1
        return true
      }

获取指定位置的元素

linkedList.prototype.get=function(index){
        if(index<0||index>this.length)return null        
        var current=this.head
        var i=0
        while(i++<index){
          current=current.next
        }
        return current.data
      }

获取指定元素的位置

linkedList.prototype.indexOf=function(data){
        var current=this.head
        var i=0
        while(i<this.length){
          if(current.data==data){
            return i
          }
          current=current.next
          i+=1
        }
        return -1
      }

修改指定位置的元素

linkedList.prototype.updata=function(index,data){
        if(index<0||index>this.length)return false
        var i=0
        var current=this.head
        while(i++<index){
          current=current.next
        }
        current.data=data
     return true }

删除指定位置的元素

linkedList.prototype.delete = function (index) {
        if (index < 0 || index > this.length) return false
        if (index == 0) {
          this.head = this.head.next
        } else {
          var i = 0
          var current = this.head
          var pro = null
          while (i++ < index) {
            pro = current
            current = current.next
            console.log(pro)
          }
          pro.next = current.next
        }
        this.length -= 1
        return true
      }

 

推荐阅读