您的位置:首页 > 其它

LeetCode 之 Merge Two Sorted Lists

2015-11-23 22:08 316 查看
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* head;
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode* l11=l1;
ListNode* l22=l2;
if(l11->val>=l22->val){
head=l22;
l22=l22->next;
}else{
head=l11;
l11=l11->next;
}
ListNode* last=head;
while(l11!=NULL||l22!=NULL){
if(l11==NULL&&l22!=NULL){
last->next=l22;
return head;
}else if(l11!=NULL&&l22==NULL){
last->next=l11;
return head;
}else if(l11->val>l22->val){
last->next=l22;
last=last->next;
l22=l22->next;
last->next=NULL;
}else{
last->next=l11;
last=last->next;
l11=l11->next;
last->next=NULL;
}
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: