JS list add elements to achieve

Statement insertion configuration to the list of elements.

function Node(ele){//定义链表中的一个元素
 this.ele = ele;//值
 this.next = null;//用来指向下一个节点的指针
}

Defined list and method

function LinkList(){//定义链表
  let length = 0;
  let head = null;
  
  //链表方法
  this.append = append;//向链表尾部添加元素
  this.insert = insert;//向指定位置插入元素
}

Add elements to the tail of the list

function append(element){
    let node = new Node(element);
    let current;
    if(this.head == null){   //链表为空时
        this.head = node;
    }else{
        current = this.head;
        while(current.next){
            current = current.next;  //通过循环得到最后一个元素
        }
        current.next = node;  //将随后一个元素的指针指向要插入的node
    }
    length++;
}

To insert elements into the specified position

function insert(position, element){
    if(position > length || position < 0 ){
        return false;
    }
    let node = new Node(element);
    let current = this.head; 
    let index = 0;
    let previous;
    if(position == 0){  //若在第一个位置添加
        node.next = current;
        this.head = node;
    }else{
        while(index++ < position){
            previous = current;
            current = current.next;
        }//找出要插入的位置previous 以及current 分别代表所插入元素位置的一前一后
        node.next = current;
        previous.next = node;
    }
    length++;
    return true;
}

The output of the list

function toString( list ){
    let current = list.head;
    let str = '';
    while(current){
        str += current.element;
        current = current.next;
    }
    return str;
}
let list = new LinkedList();
list.append(11);
list.append(22);
console.log(toString(list));  
Published an original article · won praise 1 · views 15

Guess you like

Origin blog.csdn.net/weixin_44054325/article/details/104804743