Skip to content

Commit

Permalink
Merge two sorted lists
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 16, 2017
1 parent 86ef526 commit 7e4e9b0
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 021_merge_two_sorted_lists/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test merge_lists.c
56 changes: 56 additions & 0 deletions 021_merge_two_sorted_lists/merge_lists.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <stdio.h>
#include <stdlib.h>

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

static struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
struct ListNode dummy, *tail = &dummy;
dummy.next = NULL;

while (l1 != NULL || l2 != NULL) {
struct ListNode *node = malloc(sizeof(*node));
node->next = NULL;
tail->next = node;
tail = node;
if (l1 != NULL) {
if (l2 != NULL) {
if (l1->val < l2->val) {
node->val = l1->val;
l1 = l1->next;
} else {
node->val = l2->val;
l2 = l2->next;
}
} else {
node->val = l1->val;
l1 = l1->next;
}
} else {
node->val = l2->val;
l2 = l2->next;
}
}

return dummy.next;
}

int main(int argc, char **argv)
{
struct ListNode l1;
l1.val = 2;
l1.next = NULL;
struct ListNode l2;
l2.val = 1;
l2.next = NULL;
struct ListNode * list = mergeTwoLists(&l1, &l2);
while (list != NULL) {
printf("%d ", list->val);
list = list->next;
}
printf("\n");
return 0;
}

0 comments on commit 7e4e9b0

Please sign in to comment.