#include <stdio.h> struct node { int data; struct node *next; }; void info(struct node *p) { if (p == NULL) { printf("merge result is NULL"); } while (p != NULL) { printf("%d ", p->data); p = p->next; } printf("\n"); } struct node* merge_r(struct node *l, struct node *m, struct node *tail) { if (l != NULL && m != NULL) { if (l->data < m->data) { tail->next = l; merge_r(l->next, m, tail->next); } else { tail->next = m; merge_r(l, m->next, tail->next); } } else if (l != NULL) { tail->next = l; } else if (m != NULL) { tail->next = m; } else { tail->next = NULL; } } /* * use recursion. */ struct node* merge1(struct node *l, struct node *m) { struct node head; head.data = 0; head.next = NULL; merge_r(l, m, &head); return head.next; } /* * without the use of recursion. */ struct node* merge(struct node *l, struct node *m) { struct node *head = NULL; struct node *tail = NULL; struct node *cur; int no; while (l != NULL && m != NULL) { if (l->data < m->data) { cur = l; no = 1; } else { cur = m; no = 2; } if (head == NULL) head = cur; if (tail == NULL) tail = cur; else { tail->next = cur; tail = tail->next; } switch (no) { case 1: l = l->next; break; case 2: m = m->next; break; default: /* impossible */ break; } } if (l != NULL) if (tail == NULL) head = l; else tail->next = l; if (m != NULL) if (tail == NULL) head = m; else tail->next = m; return head; } void test1() { printf("=== test1 \n"); struct node l1, l2, m1, m2, m3; l1.data = 2; l1.next = &l2; l2.data = 7; l2.next = NULL; m1.data = 1; m1.next = &m2; m2.data = 10; m2.next = &m3; m3.data = 11; m3.next = NULL; struct node *result = merge(&l1, &m1); info(result); } void test2() { printf("=== test2 \n"); struct node *result; result = merge(NULL, NULL); info(result); } void test3() { printf("=== test3 \n"); struct node l1, l2; l1.data = 2; l1.next = &l2; l2.data = 7; l2.next = NULL; info(merge(&l1, NULL)); } void test4() { printf("=== test3 \n"); struct node m1, m2, m3; m1.data = 1; m1.next = &m2; m2.data = 10; m2.next = &m3; m3.data = 11; m3.next = NULL; struct node *result = merge(NULL, &m1); info(result); } int main(int argc, const char *argv[]) { test1(); test2(); test3(); test4(); return 0; }