您的位置:首页 > 其它

leetcode刷题日记——Merge Two Sorted Lists

2015-12-18 12:56 603 查看
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) {
if(l1==NULL&&l2==NULL) return NULL;
else if(l1==NULL) return l2;
else if(l2==NULL) return l1;
else{
ListNode *p=l1,*q=l2,*head=NULL,*m=NULL;
while(p&&q){
if(p->val<=q->val){
if(head==NULL){
m=p;
p=p->next;
m->next=NULL;
head=m;
}
else{
m->next=p;
p=p->next;
m=m->next;
m->next=NULL;
}

}
else {
if(head==NULL){
m=q;
q=q->next;
m->next=NULL;
head=m;
}
else{
m->next=q;
q=q->next;
m=m->next;
m->next=NULL;
}
}
}
if(p){
m->next=p;
}
else if(q){
m->next=q;
}
return head;

}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: