单链表排序

写得很复杂,没有写在一个函数中,而是分了三个函数,也没去仔细检查,写在这方便查看,有错大家就指出哈

结构体定义为:

typedef struct _list
{
	int data;
	int key;
	struct _list *next;
}LIST;


要求按字段data大小排序
思路:

1. 找到字段data最小的节点

2.将步骤1中找到的节点移至头节点

3.移动指针,重复步骤1、2,为剩余链表节点排序,直至链表结尾

主要实现三个函数,如下:

//找最小字段节点的前向节点指针并返回,若为头节点,则返回NULL
LIST* findMinNodePrePtr(LIST* pList)
{
	if (NULL == pList)
		return NULL;

	LIST *pre = NULL;
	LIST *current = pList->next;
	LIST *q = pList;
	int minValue = pList->data;

	while (current)
	{
		if (minValue > current->data)
		{
			minValue = current->data;
			pre = q;
		}
		current = current->next;
		q = q->next;
	}

	return pre;
}

//将最小节点移至头节点
LIST* moveMinNodeToFront(LIST **pList)
{
	if (NULL == *pList)
		return NULL;

	LIST *pre = findMinNodePrePtr(*pList);
	if (NULL == pre)
		return *pList;

	LIST *current = pre->next;
	pre->next = current->next;
	current->next = *pList;
	*pList = current;

	return *pList;
}

//单链表按字段排序
LIST* sortList(LIST **pList)
{
	if (NULL == *pList)
		return NULL;

	*pList = moveMinNodeToFront(pList);
	LIST *current = (*pList)->next;
	LIST *temp = *pList;
	while (current)
	{
		moveMinNodeToFront(&current);
		temp->next = current;
		current = current->next;
		temp = temp->next;
	}
	
	return *pList;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值