Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
List* mergeTwoLists(List* l1,List* l2) { List* head =NULL,*pre,*temp; if(l1 == NULL) return l2; if(l2 == NULL) return l1; while(l1 != NULL && l2 != NULL) { if(head ==NULL && l1->value < l2->value) { head = l1; pre = head; l1 = l1->next; continue; } if(head == NULL && l1->value > l2->value) { head = l2; pre = head; l2 = l2->next; continue; } if(l1->value <= l2->value) { temp = l1->next; l1->next = pre->next; pre->next = l1; l1 = temp; pre = pre->next; } else { temp = l2->next; l2->next = pre->next; pre->next = l2; l2 = temp; pre = pre->next; } } if(l1 == NULL) pre->next = l2; if(l2 == NULL) pre->next = l1; return head; }
Merge Two Sorted Lists--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/45022005