写得很复杂,没有写在一个函数中,而是分了三个函数,也没去仔细检查,写在这方便查看,有错大家就指出哈
结构体定义为:
typedef struct _list
{
int data;
int key;
struct _list *next;
}LIST;
思路:
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(¤t);
temp->next = current;
current = current->next;
temp = temp->next;
}
return *pList;
}