[Leetcode] Merge Two Sorted Lists
2014-08-18 11:21
495 查看
题目: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.
纯链表拆分操作,代码如下:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if(!l1) return l2;
if(!l2) return l1;
ListNode * head=l1; //把1一直当做新头结点
ListNode * pre=NULL;
while(l1 !=NULL && l2 !=NULL)
{
if( l2->val < l1->val ) //2比1小,就要插到前面
{
ListNode *tmp=l2->next;
l2->next=l1;
if(pre ==NULL) head=l2; //如果1是头结点,更新头
else pre->next=l2; //加入2
pre=l2; //1后移一位
l2=tmp; //2后移一位
}
else
{
pre=l1;
l1=l1->next; //2的点比1的大,直接1右移
}
}
if(l1 ==NULL && l2 !=NULL) //跳出循环说明2后面的都比1大,直接接在后面
pre->next=l2;
return head;
}
纯链表拆分操作,代码如下:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if(!l1) return l2;
if(!l2) return l1;
ListNode * head=l1; //把1一直当做新头结点
ListNode * pre=NULL;
while(l1 !=NULL && l2 !=NULL)
{
if( l2->val < l1->val ) //2比1小,就要插到前面
{
ListNode *tmp=l2->next;
l2->next=l1;
if(pre ==NULL) head=l2; //如果1是头结点,更新头
else pre->next=l2; //加入2
pre=l2; //1后移一位
l2=tmp; //2后移一位
}
else
{
pre=l1;
l1=l1->next; //2的点比1的大,直接1右移
}
}
if(l1 ==NULL && l2 !=NULL) //跳出循环说明2后面的都比1大,直接接在后面
pre->next=l2;
return head;
}
相关文章推荐
- Leetcode|Merge Two Sorted Lists
- LeetCodet题解--21. Merge Two Sorted Lists(合并两个排序好的链表)
- 21 - Merge Two Sorted Lists - LeetCode
- leetcode第21题——*Merge Two Sorted Lists
- leetcode 21 Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- 【LeetCode】Merge Two Sorted Lists
- leetcode第一刷_Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- leetcode 21: Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- leetcode(21). Merge Two Sorted Lists
- [leetcode]_Merge Two Sorted Lists
- 【Leetcode】Merge Two Sorted Lists
- Leetcode:Merge Two Sorted Lists(Importance!)
- [LeetCode] Merge Two Sorted Lists
- leetcode笔记:Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- Leetcode (2) Merge Two Sorted Lists