您的位置:首页 > 其它

和大神们学习每天一题(leetcode)-Merge Two Sorted Lists

2014-12-08 15:37 183 查看
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.

class Solution
{
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if (l2 == NULL)
return l1;
if (l1 == NULL)
{
l1 = l2;
return l1;
}
ListNode * LNpL1 = l1, *LNpL2 = l2, *LNpFor = NULL;//指针1和2分别指向两个链表的头
while (LNpL1 != NULL&&LNpL2 != NULL)//遍历两个链表知道其中一个完全遍历
{
if (LNpL1->val < LNpL2->val)//比较当前指针指向节点的值,指针1的值如果小于2的值则指针1向后移动
{
LNpFor = LNpL1;
LNpL1 = LNpL1->next;
}
else//否则将指针2指向的结点插入到指针1指向结点的前面
{
if (LNpFor == NULL)
{
LNpFor = LNpL2;
l1 = LNpFor;
}
else
{
LNpFor->next = LNpL2;
LNpFor = LNpFor->next;
}
LNpL2 = LNpL2->next;
LNpFor->next = LNpL1;
}
}
if (LNpL1 == NULL)//如果链表1遍历完全,则将链表2剩余结点接在链表1后面
{
LNpFor->next = LNpL2;
}
return l1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: