代码:
1 #include<iostream> 2 3 using namespace std; 4 5 struct ListNode { 6 int val; 7 ListNode *next; 8 ListNode(int x) : val(x), next(NULL) {} 9 }; 10 11 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 12 if (l1 == NULL) 13 return l2; 14 if (l2 == NULL) 15 return l1; 16 ListNode *p = l1, *q = l2; 17 ListNode *head; 18 if (l1->val < l2->val) 19 { 20 head = l1; 21 p = p->next; 22 } 23 else 24 { 25 head = l2; 26 q = q->next; 27 } 28 ListNode *m = head; 29 while (p != NULL&&q != NULL) 30 { 31 if (p->val < q->val) 32 { 33 m->next = p; 34 p = p->next; 35 m = m->next; 36 } 37 else 38 { 39 m->next = q; 40 q = q->next; 41 m = m->next; 42 } 43 } 44 if (p == NULL) 45 { 46 m->next = q; 47 } 48 else 49 { 50 m -> next = p; 51 } 52 return head; 53 } 54 55 int main() 56 { 57 ListNode *a1 = (ListNode *)malloc(sizeof(ListNode)); 58 ListNode *a2 = (ListNode *)malloc(sizeof(ListNode)); 59 ListNode *a3 = (ListNode *)malloc(sizeof(ListNode)); 60 ListNode *a4 = (ListNode *)malloc(sizeof(ListNode)); 61 ListNode *a5 = (ListNode *)malloc(sizeof(ListNode)); 62 a1->val = 2; 63 a2->val = 3; 64 a3->val = 6; 65 a4->val = 9; 66 a1->next = NULL; 67 a2->next = a3; 68 a3->next = a4; 69 a4->next = NULL; 70 ListNode *b1 = (ListNode *)malloc(sizeof(ListNode)); 71 ListNode *b2 = (ListNode *)malloc(sizeof(ListNode)); 72 ListNode *b3 = (ListNode *)malloc(sizeof(ListNode)); 73 ListNode *b4 = (ListNode *)malloc(sizeof(ListNode)); 74 ListNode *b5 = NULL; 75 b1->val = 1; 76 b2->val = 62; 77 b3->val = 68; 78 b4->val = 90; 79 b1->next = NULL; 80 b2->next = b3; 81 b3->next = b4; 82 b4->next = NULL; 83 ListNode *m = mergeTwoLists(a1, b1); 84 for (; m != NULL; m = m->next) 85 cout << m->val << endl; 86 }