單鏈表排序

來源:互聯網
上載者:User

寫得很複雜,沒有寫在一個函數中,而是分了三個函數,也沒去仔細檢查,寫在這方便查看,有錯大家就指出哈

結構體定義為:

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(&current);temp->next = current;current = current->next;temp = temp->next;}return *pList;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.