了解過鏈表的都知道可以將鏈表中的每個節點看成是一個對象,這個對象中有兩個屬性,一個是該節點的值,一個是該節點的下一個節點的地址。
對鏈表進行插入和刪除操作比數組要方便。接下來我們來看一下具體怎么用代碼去實現鏈表的基本操作:
function LinkList(){ //新元素構造 var Node = function (element){ this.element = element; this.next = null; } var length = 0;//鏈表長度 var head = null;//頭結點 /** * 向鏈表添加新元素 * @param element * @returns {Node|Node} */ this.append = function (element){ var node = new Node(element); var current; if (head === null){ head = node; }else{ current = head; while (current.next){//遍歷鏈表找到最后一個位置 current = current.next; } current.next = node; } length ++; return head; } /** * 刪除鏈表某個位置的結點 * @param option * @returns {null|boolean} */ this.remove = function (option){ var current = head; var previous; var index = 1; if (option > 0 && option <= length){ if (option === 1){ head = current.next; }else{ while (index++ < option){//注意index++ 等於option時還會執行一次循環體。 previous = current; current = current.next; } //循環結束后current就是要刪除的結點 previous.next = current.next; } length--; return head }else{ return false; } } /** * 向鏈表的指定位置插入結點 * @param option * @param element * @returns {null|boolean} */ this.insert = function (option,element){ var node = new Node(element); var current = head; var index = 0; var previous; if (option > -1 && option <= length){ if (option === 0){ node.next = current; head = node; }else{ while (index++ < option){ previous = current; current = current.next; } previous.next = node; node.next = current; } length++; return head; }else{ return false; } } //返回長度 this.getLength = function (){ return length; } //返回鏈表元素 this.getElement = function (){ var current = head; var string = head.element; while (current.next){ current = current.next; string += ' ' + current.element } return string; } //返回鏈表 this.getHead = function (){ return head; } } var link = new LinkList(); console.log('================添加結點=====================') link.append(5); link.append(8); link.append(6); link.append(7); console.log("鏈表長度:" + link.getLength()); console.log("結點元素:" + link.getElement()); console.log(link.getHead()); console.log('================刪除第二個結點========================') link.remove(5); console.log("鏈表長度:" + link.getLength()); console.log("結點元素:" + link.getElement()); console.log(link.getHead()); console.log('=============在第一個位置插入結點結點===================') link.insert(0,66); console.log("鏈表長度:" + link.getLength()); console.log("結點元素:" + link.getElement()); console.log(link.getHead());
在寫這段代碼時我在插入結點這一塊踩過一個坑,我本來想讓插入結點的option和刪除節點的option一樣,都是表示第幾個位置,但是代碼寫好后發現最后一個位置沒有辦法插入。
后面我一步一步寫下while循環每一個循環結果后發現previous和current兩個指針只能到達最后兩個結點,所以我們必須要從0開始遍歷插入,前移一個位置。