题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
#include <stdio.h> struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) { struct ListNode* head = NULL; struct ListNode* tmp = NULL; if (pHead1 == NULL) { return pHead2; } if (pHead2 == NULL) { return pHead1; } if (pHead1->val < pHead2->val) { head = pHead1; pHead1 = pHead1->next; } else { head = pHead2; pHead2 = pHead2->next; } tmp = head; while (tmp) { if (pHead1 == NULL) { tmp->next = pHead2; break; } if (pHead2 == NULL) { tmp->next = pHead1; break; } if (pHead1->val < pHead2->val) { tmp->next = pHead1; pHead1 = pHead1->next; } else { tmp->next = pHead2; pHead2 = pHead2->next; } tmp = tmp->next; } return head; } struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) { int index = 0; struct ListNode* head = NULL; if(listsLen==1) { return lists[0]; } for(index=0;index<listsLen;index++) { head = Merge(head, lists[index]); } return head; }