极客时间数据结构与算法之美笔记7

链表节点插入

new_node->next = p->next;
p->next = new_node;

链表节点删除

p->next = p->next->next;

上述两个链表操作,对于空节点或者最后一个节点场景,会有异常。

带有头节点(哨兵节点)的链表思路:

这个思路形似用空间换时间
即用增加包裹节点减少一个判断语句
减少一个判断语句不仅提高电脑运行速度,也减轻人脑阅读代码负担。

示例如下:

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)
);



单链表反转

链表中环的检测

两个有序的链表合并

删除链表倒数第 n 个结点

求链表的中间结点

删除链表中的重复节点

posted @ 2019-07-10 09:54  草珊瑚  阅读(411)  评论(0编辑  收藏  举报