aboutsummaryrefslogtreecommitdiff
path: root/merge_k_sorted_list.c
blob: b5f8ddc8b4eb09f7a878f51d78a3d863b737d573 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 23. Merge k Sorted Lists
#include <stddef.h>
#include <stdlib.h>

struct ListNode {
  int val;
  struct ListNode *next;
};

struct ListNode *mergeKLists(struct ListNode **lists, int lists_size) {
  if (lists_size == 0)
    return NULL;
  struct ListNode *head = malloc(sizeof(struct ListNode));
  struct ListNode *tmp = head, *min;
  int id;
  while (1) {
    min = lists[0];
    id = 0;
    for (int i = 1; i < lists_size; i++) {
      if (min == NULL && lists[i]) {
        min = lists[i];
        id = i;
      }
      if (lists[i] == NULL)
        continue;
      else {
        if (lists[i]->val < min->val) {
          min = lists[i];
          id = i;
        }
      }
    }
    if (min == NULL) {
      tmp->next = NULL;
      break;
    }
    tmp->next = min;
    tmp = tmp->next;
    lists[id] = lists[id]->next;
    while (lists[id] && lists[id]->val == tmp->val) {
      tmp->next = lists[id];
      tmp = tmp->next;
      lists[id] = lists[id]->next;
    }
  }
  return head->next;
}