您的位置:首页 > 其它

LeetCode21. Merge Two Sorted Lists

2016-10-13 23:31 405 查看

LeetCode21. Merge Two Sorted Lists

原地址

题目描述

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.


思路

可以设置一个新链表newhead,逐个比较l1,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) {
//链表为空
if(l1==NULL || l2==NULL)
{
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
}

//确定新链表头结点
ListNode* newhead=new ListNode(0);
ListNode* p3;
p3=newhead;

while(l1 && l2){
ListNode* tmp=new ListNode(0);
if(l1->val<=l2->val){
tmp->val=l1->val;
p3->next=tmp;
p3=tmp;
l1=l1->next;
}
else if(l1->val>l2->val){
tmp->val=l2->val;
p3->next=tmp;
p3=tmp;
l2=l2->next;
}

}

//剩余结点
while(l1){
ListNode* tmp=new ListNode(0);
tmp->val=l1->val;
p3->next=tmp;
p3=tmp;
l1=l1->next;
}
while(l2){
ListNode* tmp=new ListNode(0);
tmp->val=l2->val;
p3->next=tmp;
p3=tmp;
l2=l2->next;
}
newhead = newhead->next;
return newhead;
}
};


ps: 之前写过几乎相同的代码,结果这一次写又出现了意想不到的错误(第一个while循环里面没有用else if而用了if,其实这时l1可能已经发生了变化)。所以说不要眼高手低,再简单的题都有可能错误。

鸡汤

细节决定成败
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 单链表