Make a Linked list-JS的雙向鏈結
const DoubleLinked = function () { const Node = function (element) { this.element = element; this.next = null; this.prev = null; } let length = 0; let head, tail; this.insert = (position, element) => { if (position > -1 && position <= length) { let node = new Node(element); let current = head; let previous; let index = 0; if (position === 0) { if (!head) { head = node; tail = node; } else { node.next = current; current.prev = node; head = node; } } else if (position === length) { current = tail; current.next = node; node.prev = current; tail = node; } else { while (index++ < position) { previous = current; current = current.next; } previous.next = node; node.prev = previous; node.next = current; current.prev = node; } length++; return head; } else { return false; } } this.removeAt = (position) => { let current = head; let previous; let index = 0; if (position > -1 && position <= length) { if (position === 0) { head = current.next; head.prev = null; }else if (position === length){ tail = tail.prev; tail.next = null; }else{ while(index++{ return head; } this.toString = ()=>{ let string = ''; let current = head; while(current){ string+=current.element; current = current.next; } return string; }; this.indexOf = (element)=>{ let index = 0; let current = head while(current){ index++; if(current.element===element){ return index; } current = current.next; } return false; } this.remove = (element) => { let index = this.indexOf(element); return this.removeAt(index); } this.append = (element) => { const node = new Node(element); let current = head; if(head===null){ head = node; tail = node; }else{ tail.next = node; node.prev = tail; tail = node; } length++; return tail; } } const DL = new DoubleLinked(); DL.insert(0,"Hi"); DL.append("Im"); DL.insert(2,"Eddie"); console.log(DL.toString()); DL.removeAt(0); console.log(DL.toString()); console.log(DL.getHead());
Published 27 Jul 2017