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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| #include <stdint.h> #include <stdio.h> #include <stdlib.h>
struct ListNode { int32_t val; struct ListNode *next; };
struct ListNode *NewListNode(int32_t val) { struct ListNode *node = calloc(1, sizeof(struct ListNode)); node->val = val; node->next = NULL; return node; }
struct ListNode *InsetrtListNode(int32_t val, struct ListNode *after) { if (after == NULL) return NULL; struct ListNode *node = NewListNode(val); node->next = after->next; after->next = node; return node; }
void FreeList(struct ListNode *head) { for (struct ListNode *next; head != NULL; head = next) { next = head->next; free(head); } }
struct ListNode *ReadList() { struct ListNode *head = NULL, *tail = head; int32_t val;
do { scanf("%d", &val); if (tail == NULL) { tail = head = NewListNode(val); } else { tail = InsetrtListNode(val, tail); } } while (getchar() != '\n' && getchar() != '\n'); return head; }
void PrintList(struct ListNode *head) { if (head == NULL) return; printf("%d", head->val); for (head = head->next; head != NULL; head = head->next) printf("->%d", head->val); printf("\n"); }
struct ListNode *Merge(struct ListNode *a, struct ListNode *b) { struct ListNode *head = NewListNode(0), *tail = head;
while (a != NULL || b != NULL) { if (b == NULL || a != NULL && a->val < b->val) { tail = InsetrtListNode(a->val, tail); a = a->next; } else { tail = InsetrtListNode(b->val, tail); b = b->next; } }
tail = head->next; free(head); return tail; }
int main() { struct ListNode *a = ReadList(); struct ListNode *b = ReadList(); struct ListNode *res = Merge(a, b);
PrintList(res);
FreeList(a); FreeList(b); FreeList(res);
return 0; }
|