單連結串列的尾插,頭插,遍歷,查詢和插入

看風景就發表於2017-05-18

單連結串列的基本結構

function Node(val,next){
    this.val = val;
    this.next = next || null;
}
1.連結串列的建立
a.尾插法,就是正常的尾部順序插入,從陣列建立連結串列
function tailCreateList(aSrc){
    var head = new Node();
    pHead = head;
    aSrc.forEach((item) => {
        var node = new Node(item);
        pHead.next = node;
        pHead = node;
    })
    return head;
}
b.頭插法,將後面的資料插入到頭部,頭結點後面,形成倒序的列表
function headCreateList(aSrc){
    var head = new Node();
    pHead = head;
    aSrc.forEach((item) => {
        var node = new Node(item);
        node.next = pHead.next;
        pHead.next = node;
    })
    return head;
}
2.連結串列的遍歷
function traverse(head,fVisit){
    if(head == null){
        return;
    }
    var cur = head.next;
    while(cur){
        fVisit && fVisit(cur);
        cur = cur.next;
    }
}
3.連結串列的查詢
function find(head,val){
    if(head == null){
        return;
    }
    var cur = head;
    while(cur && cur.val != val){
        cur = cur.next;
    }
    return cur;
}
4.連結串列的插入
function insert(head,val,newVal){
    if(head == null){
        return;
    }
    var cur = head;
    while(cur && cur.val != val){
        cur = cur.next;
    }
    if(cur){
        var newNode = new Node(newVal);
        newNode.next = cur.next;
        cur.next = newNode;
    }
}

 

相關文章