单链表:删除带头节点单链表中最小值所有在的节点

2022-02-24 20:16:24 浏览数 (1)

思路:用两对前驱和后继节点,分别比较当前节点的前驱和后继以及最小值界定啊的前驱和后继。 遍历完整个链表,删除最小值节点即可。

代码语言:javascript复制
struct node {
	int val;
	node *next;
};


void deleteMin(node *head) {
	node *p = head, *q = head->next;
	node *premin = head, *pmin = head->next;
	while (q) {
		if (q->val < pmin->val) {
			pmin = q;
			premin = p;
			p = p->next, q = q->next;
		} else {
			p = p->next;
			q = q->next;
		}
		node *del = pmin;
		premin->next = pmin->next;
		delete del;
	}
}

0 人点赞