题目描述:
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.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *temp=l2,*last_temp=NULL,*random;
while(l1!=NULL){
temp = l2;
while(temp!=NULL&&l1->val>temp->val){
last_temp = temp;
temp = temp->next;
}
/*if(last_temp!=NULL)
cout<<"last_temp = "<<last_temp->val<<endl;
if(temp!=NULL)
cout<<"temp ="<<temp->val<<endl;
*/
random = l1;
l1 = l1->next;
//插入头
if(last_temp==NULL){
random->next = l2;
l2 = random;
}else if(temp==NULL){//插入尾部
last_temp->next = random;
random->next = NULL;
}else if(temp!=NULL){//插入中间
last_temp->next=random;
random->next = temp;
}
random = l2;
while(random!=NULL){
//cout<<random->val<<" ";
random = random->next;
}
//cout<<endl;
}
return l2;
}
};