数据结构与算法JavaScript描述读书笔记(js实现链表-单链表)

单链表

//创建构造函数创建节点
function Node(element){
    this.element = element;
    this.next = null;
}
//链表的构造函数
 function LList(){
    this.head = new Node('head');
    this.insert = insert;
    this.remove = remove;
    this.display = display;
    this.find = find;
    this.prefind = prefind;
 }
 function insert(newElement,item){
    var cur = this.find(item);
    var node = new Node(newElement);
    if(cur == null){
        alert('没有找到插入位置');
    }else{
        node.next = cur.next;
        cur.next = node;
    }
 }
 function find(item){
    var cur = this.head;
    while(cur.element != item){
        cur = cur.next;
    }
    return cur;
 }
 function display() {
     var cur = this.head;
     var str = '';
     while (cur.next != null){
        str += cur.next.element+'->';
        cur = cur.next;
     }
     return str;
 }
 function prefind(item){
    var cur = this.head;
    while(cur.next.element != item && cur.next != null){
        cur = cur.next;
    }
    return cur;
 }
 function remove(item){
    var pre = this.prefind(item);
    if(pre.next != null){
        pre.next = pre.next.next;
    }
 }

猜你喜欢

转载自blog.csdn.net/qq_37200686/article/details/83107795