資料結構與演算法JavaScript描述讀書筆記(js實現連結串列-單鏈表)
阿新 • • 發佈:2018-11-04
單鏈表
//建立建構函式建立節點 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; } }