链表节点插入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
求链表的中间结点
删除链表中的重复节点