https://leetcode-cn.com/problems/merge-two-sorted-lists/
思路(如下图):谁小放谁前面,但是记得用next保存下一个位置。
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){ if(list1==NULL) return list2; if(list2==NULL) return list1; struct ListNode* cur1=list1; struct ListNode* next1=list1; struct ListNode* cur2=list2; struct ListNode* next2=list2; struct ListNode* newhead=NULL; struct ListNode* newcur=NULL; while(cur1!=NULL && cur2!=NULL) { if(cur1->val<cur2->val) { if(newhead==NULL) { next1=cur1->next; newhead=cur1; newcur=cur1; cur1=next1; } else { next1=cur1->next; newcur->next=cur1; newcur=cur1; cur1=next1; } } else { if(newhead==NULL) { next2=cur2->next; newhead=cur2; newcur=cur2; cur2=next2; } else { next2=cur2->next; newcur->next=cur2; newcur=cur2; cur2=next2; } } } //谁不为空就是没插完 if(cur1!=NULL) { newcur->next=cur1; } else { newcur->next=cur2; } return newhead; }