题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类一维数组
* @param listsLen int lists数组长度
* @return ListNode类
*/
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode* temp1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* temp2 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode) * 5001);
temp1 = pHead1;
temp2 = pHead2;
struct ListNode* cur ;
cur = result;
while((temp1 != NULL) || (temp2 != NULL))
{
if((temp1 != NULL) && (temp2 != NULL))
{
if(temp1->val <= temp2->val)
{
printf("111 p1 %d p2 %d cur %d\n",temp1->val, temp2->val, cur->val);
cur->next = temp1;
cur = temp1;
temp1 = temp1->next;
} else {
printf("222 p1 %d p2 %d cur %d\n",temp1->val, temp2->val, cur->val);
cur->next = temp2;
cur = temp2;
temp2 = temp2->next;
}
} else if((temp1 == NULL)) {
cur->next = temp2;
cur = temp2;
temp2 = NULL;
} else if((temp2 == NULL)) {
cur->next = temp1;
cur = temp1;
temp1 = NULL;
}
}
printf("=== %d\n", result->val );
return result->next;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
// write code here
struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode) * 5001);
result = NULL;
int count = listsLen;
while(count)
{
printf("=== count %d\n", count );
result = Merge(result, lists[(listsLen-count)]);
count--;
}
return result;
}