Linked List 連結串列
阿新 • • 發佈:2020-08-19
1. 連結串列,常見的有單鏈表,雙向連結串列,迴圈連結串列
2. 雙向連結串列是常見的空間換時間的策略
3. 淘汰快取的做法一般有幾個,一般用連結串列結構,常見的策略有三種:先進先出策略 FIFO(First In,First Out)、最少使用策略 LFU(Least Frequently Used)、最近最少使用策略 LRU(Least Recently Used)。
functionListNode(val){ this.val=val; this.next=null; } 4.常見的連結串列操作: 1.單鏈表反轉2.連結串列中環的檢測
3.兩個有序連結串列合併
4.刪除連結串列倒數第n個節點
function ListNode(val) { this.val = val; this.next = null; } // way1 先找出最小,同時構造 var mergeKLists = function (lists) { if (lists == null || lists.length <= 1) { return lists; } let res = null; let tail = null; while (true) { let isAllNull = true; let curMin= Infinity; let curMinIndex = 0; for (let i = 0; i < lists.length; i++) { if (lists[i] && curMin > lists[i].val) { curMin = lists[i].val; curMinIndex = i; } if (lists[i]) { isAllNull = false; } } if (lists[curMinIndex]) { lists[curMinIndex]= lists[curMinIndex].next; } if (isAllNull) { break; } if (!res) { res = {}; res.val = curMin; res.next = null; } else { let node = new ListNode(curMin); if (res.next === null) { res.next = node; } else { tail.next = node; } tail = node; } } return res; }; var node1 = new ListNode(1); var node3 = new ListNode(3); node1.next = node3; var node2 = new ListNode(2); var node4 = new ListNode(4); var node5 = new ListNode(5); node2.next = node4; node4.next = node5; console.log(mergeKLists([node1, node2])); //way2 先合併,排序,最後生成 var mergeKLists = function (lists) { if (!lists || lists.length == 0) return null; let arr = []; debugger; let res = new ListNode(0); lists.forEach(list => { let cur = list; while (cur) { arr.push(cur.val); cur = cur.next; } }); let cur = res; arr .sort((a, b) => a - b) .forEach(val => { let node = new ListNode(val); cur.next = node; cur = cur.next; }); return res.next; };