您好,登錄后才能下訂單哦!
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
給定k個排序了的鏈表,合并k個鏈表成一個排序鏈表。
本程序思路:
1)首先得到K個鏈表的長度和存在len中
2)從K個鏈表中找到值最小的那個節點,把該節點添加到合并鏈表中
3)重復len次即可把所有節點添加到合并鏈表中。
注意事項:
1)K個鏈表中有的鏈表全部添加完會變成空鏈表,應做相應的處理
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) { struct ListNode *list = NULL; /*獲取鏈表長度*/ int cnt = 0, len = 0; for ( ; cnt < listsSize; cnt++ ) { list = lists[cnt]; for ( ; list; list = list->next ) { len += 1; } } list = NULL; struct ListNode **head = &list; struct ListNode *node = NULL; int key = 0; for ( cnt = 0; cnt < len; cnt++ ) { int index = 0; int nullSizes = 0; /*獲取鏈表中空鏈表數量*/ for ( index = 0; index < listsSize; index++ ) { if ( lists[index] == NULL ) { nullSizes += 1; } } /*刪掉鏈表數組中空鏈表,組成新的鏈表數組*/ int nulls = 0; int flag = 0; for ( nulls = 0; nulls < nullSizes; nulls++ ) { flag = 0; for ( index = 0; index < listsSize; index++ ) { if ( lists[index] == NULL ) { lists[index] = lists[index + 1]; flag = 1; } else if ( flag == 1) { lists[index] = lists[index + 1]; } } } /*刪掉空鏈表并及時修改現存鏈表數量*/ if ( flag == 1 ) { listsSize -= nullSizes; } /*找到所有鏈表中值最小的節點*/ int min = INT_MAX; for ( index = 0; index < listsSize; index++ ) { if ( lists[index]->val < min ) { min = lists[index]->val; node = lists[index]; key = index; } } /*把最小節點添加到合并鏈表中*/ (*head) = node; node = node->next; head = &(*head)->next; /*最小值所在鏈表往后移*/ lists[key] = node; } return list; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。