forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
86ef526
commit 7e4e9b0
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test merge_lists.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |