王道数据结构课后代码题p40 4.在带头结点的单链表L中删除一个最小值结点的高效算法(假设最小值唯一) (c语言代码实现)

 本题代码为

void deletemin(linklist* L)//找到最小值并删除
{
	lnode* p = (*L)->next, * pre = *L;
	lnode* s = p,*spre=pre;
	while (p != NULL)//找到最小值
	{
		if (p->data < s->data)
		{
			s = p;
			spre = pre;
		}
		p = p->next;
		pre = pre->next;
	}
	p = s->next;
	spre->next = p;
	free(s);
}

完整测试代码

#include
#include
typedef struct lnode
{
	int data;
	struct lnode* next;
}lnode,*linklist;
int n = 4;
int a[4] = { 1,2,3,4 };
void buildlinklist(linklist* L)
{
	*L = (lnode*)malloc(sizeof(lnode));
	(*L)->next = NULL;
	lnode* s = *L, * r = *L;
	int i = 0;
	for (i = 0; i < n; i++)
	{
		s = (lnode*)malloc(sizeof(lnode));
		s->data = a[i];
		s->next = r->next;
		r->next = s;
		r = s;
	}
	r->next = NULL;
}
void deletemin(linklist* L)
{
	lnode* p = (*L)->next, * pre = *L;
	lnode* s = p,*spre=pre;
	while (p != NULL)//找到最小值
	{
		if (p->data < s->data)
		{
			s = p;
			spre = pre;
		}
		p = p->next;
		pre = pre->next;
	}
	p = s->next;
	spre->next = p;
	free(s);
}
void print(linklist* L)
{
	lnode* p = (*L)->next;
	while (p != NULL)
	{
		printf("%d", p->data);
		p = p->next;
	}
}
int main()
{
	linklist L;
	buildlinklist(&L);
	printf("原始单链表为:");
	print(&L);
	deletemin(&L);
	printf("\n删除最小值后的单链表为:");
	print(&L);
	return 0;
}

你可能感兴趣的:(王道课后习题单链表,数据结构,算法,c语言,链表)