寫得很複雜,沒有寫在一個函數中,而是分了三個函數,也沒去仔細檢查,寫在這方便查看,有錯大家就指出哈
結構體定義為:
typedef struct _list{int data;int key;struct _list *next;}LIST;
要求按欄位data大小排序
思路:
1. 找到欄位data最小的節點
2.將步驟1中找到的節點移至前端節點
3.移動指標,重複步驟1、2,為剩餘鏈表節點排序,直至鏈表結尾
主要實現三個函數,如下:
//找最小欄位節點的前向節點指標並返回,若為前端節點,則返回NULLLIST* 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;}