Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

这题要求合并两个已经排好序的链表,很简单的题目,直接上代码:

  1. class Solution {
  2. public:
  3. ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
  4. ListNode dummy(0);
  5. ListNode* p = &dummy;
  6. while(l1 && l2) {
  7. int val1 = l1->val;
  8. int val2 = l2->val;
  9. //哪个节点小,就挂载,同时移动到下一个节点
  10. if(val1 < val2) {
  11. p->next = l1;
  12. p = l1;
  13. l1 = l1->next;
  14. } else {
  15. p->next = l2;
  16. p = l2;
  17. l2 = l2->next;
  18. }
  19. }
  20. //这里处理还未挂载的节点
  21. if(l1) {
  22. p->next = l1;
  23. } else if(l2) {
  24. p->next = l2;
  25. }
  26. return dummy.next;
  27. }
  28. };

Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

这题需要合并k个排好序的链表,我们采用divide and conquer的方法,首先两两合并,然后再将先前合并的继续两两合并。时间复杂度为O(NlgN)。

代码如下:

  1. class Solution {
  2. public:
  3. ListNode *mergeKLists(vector<ListNode *> &lists) {
  4. if(lists.empty()) {
  5. return NULL;
  6. }
  7. int n = lists.size();
  8. while(n > 1) {
  9. int k = (n + 1) / 2;
  10. for(int i = 0; i < n / 2; i++) {
  11. //合并i和i + k的链表,并放到i位置
  12. lists[i] = merge2List(lists[i], lists[i + k]);
  13. }
  14. //下个循环只需要处理前k个链表了
  15. n = k;
  16. }
  17. return lists[0];
  18. }
  19. ListNode* merge2List(ListNode* n1, ListNode* n2) {
  20. ListNode dummy(0);
  21. ListNode* p = &dummy;
  22. while(n1 && n2) {
  23. if(n1->val < n2->val) {
  24. p->next = n1;
  25. n1 = n1->next;
  26. } else {
  27. p->next = n2;
  28. n2 = n2->next;
  29. }
  30. p = p->next;
  31. }
  32. if(n1) {
  33. p->next = n1;
  34. } else if(n2) {
  35. p->next = n2;
  36. }
  37. return dummy.next;
  38. }
  39. };