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.
该题是要求合并两个已排序的列表,根据stl库里list的sort,这里的排序是指从小到大排序
在最终的链表前再加一个节点head,使得程序的思路很清晰,那么分三种情况来处理:
对于list l1 和 list l2,可能下一个要添加的元素是要比较两个链表中的元素,找到较小的添加;
也可能是只有l1中的元素可以添加;也可能是只有l2中的元素可以添加;
所以可以写出如下程序
/**
* 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* head= new ListNode(0);
ListNode* p=head;//head->next为返回的指针
while(1)
{
if(l1 && l2){
if(l1->val<l2->val){
p->next=l1;
p=l1;
l1=l1->next;
}
else{
p->next=l2;
p=l2;
l2=l2->next;
}
}
else if(l1 && l2==NULL){
p->next=l1;
break;
}
else if(l1==NULL && l2){
p->next=l2;
break;
}
else{
break;
}
}
return head->next;
}
};