鏈表節點插入javascript
new_node->next = p->next; p->next = new_node;
鏈表節點刪除java
p->next = p->next->next;
上述兩個鏈表操做,對於空節點或者最後一個節點場景,會有異常。node
帶有頭節點(哨兵節點)的鏈表思路:this
這個思路形似用空間換時間
。
即用增長包裹節點
換減小一個判斷語句
。
減小一個判斷語句
不只提升電腦運行速度,也減輕人腦閱讀代碼負擔。code
示例以下:ip
const log = console.log.bind(this); const obj = {key:null, next:null}; // 帶有頭節點的空鏈表 const linked_list_with_head = {next:null}; // 帶有頭節點的非空鏈表 // key是惟一的 const demo = {next:{key:99,next:{key:88,next:{key:77,next:null}}}}; const find_with_head = (L, key)=>{ let node = L.next; while(key !== node.key && node !== null){ node = node.next; } return node; }; const Insert_with_head = (L,x)=>{ x.next = L.next; L.next = x; return L }; const delete_with_head = (L, x)=>{ let prev = L; while(prev.next !== x){ prev = prev.next; } prev.next = x.next; return L; } const one_node = find_with_head(demo, 77); delete_with_head(demo, one_node); log( JSON.stringify(demo) );
單鏈表反轉string
鏈表中環的檢測it
兩個有序的鏈表合併console
刪除鏈表倒數第 n 個結點class
求鏈表的中間結點
刪除鏈表中的重複節點