【資料結構】單鏈表常用方法實現
阿新 • • 發佈:2021-09-28
連結串列結構
連結串列配合圖才好理解,所以畫了以下這些圖幫助理解連結串列工作的流程
插入連結串列示意圖
第一種情況:在連結串列開頭插入元素
第二種情況:在連結串列除開頭的任意位置插入元素
刪除連結串列元素示意圖
第一種情況:
第二種情況:
程式碼實現
class Node { constructor(element) { this.element = element; this.next = null; } } class LinkedList { constructor() { this.head = null; this.length = 0; } //在連結串列尾部插入元素 append(element) { let newNode = new Node(element), current; if(this.head === null) { this.head = newNode; } else { current = this.head; while(current.next) { current = current.next; } current.next = newNode; } this.length++; } //在連結串列任意位置插入元素 insert(element,position) { let newNode = new Node(element), current = this.head, previous, index = 0; if(position >= 0 && position <= this.length) { if(position === 0) { this.head = newNode; newNode.next = current; } else { while(index++ < position) { previous = current; //記錄每一個元素的前一項 current = current.next; //current指向下一個元素的資料域 } previous.next = newNode; //前一項的指標域指向插入的新元素 newNode.next = current; //新元素的指標域指向後面的元素 } this.length++; return true; }else { return false; } } //獲取任意位置元素 getElem(position) { let current = this.head, index = 0; //判斷越界 if(position < 0 || position > this.length - 1) { return null; } else { // 直到找到index ++到postion,說明已經到了要找的元素位置 while(index++ < position) { current = current.next; } return current.element; //直接返回元素的element } } //獲取任意位置元素的索引 indexOf(element) { let current = this.head, index = 0; while(current) { if(current.element === element) { return index; } index++; current = current.next; } return -1; //若沒找到返回-1 } //刪除任意位置的元素 removeAt(position) { let current = this.head, previous, index = 0; if(position < 0 || position > this.length - 1) { return null; } else { if(position === 0) { this.head = current.next; } else { // 迴圈到要刪除的位置 while(index++ < position) { previous = current; //記錄current前一項 current = current.next; //current往後移 } current = current.next; //current向後移 previous.next = current; //previous的指標域直接連結向後移過的current } this.length--; return true; } } //更新任意位置的元素 update(element,position) { this.removeAt(position); //先刪除這個位置的元素 return this.insert(element,position); //再插入更新元素 } }