js-資料結構-連結串列
阿新 • • 發佈:2020-11-05
陣列
依次儲存
- 缺點: 對陣列做刪除或者插入的時候,可能需要移動大量的元素
棧 : push,pop
佇列:push,shift
雙向連結串列結構
- 可重複新增key值相同的元素
- 記錄插入順序
class ListNode { constructor(key) { // 指向前一個節點 this.prev = null; // 指向後一個節點 this.next = null; // 節點的資料(或者用於查詢的鍵) this.key = key; } } /** * 雙向連結串列 */ class List { constructor() { this.head = null; //引用上一個資料 } static createNode(key) { return new ListNode(key); } insert(node) { node.prev = null; //父 node.next = this.head; //子 if (this.head) { this.head.prev = node; } this.head = node; } search(key) { let node = this.head; while (node !== null && node.key !== key) { //從底部查詢,查詢後退出 node = node.next; } return node; } delete(node) { const { prev, next } = node; delete node.prev; delete node.next; if (node === this.head) { this.head = next; } if (prev) { prev.next = next; } if (next) { next.prev = prev; } } } let pop = new List(); pop.insert(List.createNode('lml1')) pop.insert(List.createNode('lml2')) pop.insert(List.createNode('lml3')) pop.insert(List.createNode('lml2')) //可重複key // // pop.insert({key:'lml1'}) // pop.insert({key:'lml2'}) // pop.insert({key:'lml3'}) console.log(pop); console.log(pop.search('lml2')); var kvArray = [["key1", "value1"], ["key2", "value2"]]; var myMap = new Map(kvArray); myMap.set('key1','lml3') console.log(Array.from(myMap)); // pop.delete(pop.search('lml2')) // console.log(pop); // console.log(pop.search('lml2'));
var a = new Set([1, 2, 3]);
var b = new Set([4, 3, 2]);
var difference = new Set([...a].filter(x => !b.has(x))); // {1}