Description
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
Analyze
给定的函数如下:
- @param l1 链表头结点(带值)
- @param l2 链表头结点(带值)
- @return 两个链表连接的新链表头结点(带值)
既然两个链表都是有序链表,那么可以从两个链表开头一个一个连接到新链表上,当一个链表链完之后,直接把另一个链表链到后面就行了
Realization
- 新链表头指针
tmp是移动的结点,由他来判断该链接哪个结点到新链表中,p 是新链表的头指针
- 主循环
先把其中一个链表遍历完,把值小的那个结点加入到新链表中
-
再把剩余的直接连接到tmp后面
-
返回
-
提交
附源代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
tmp->next = NULL;
struct ListNode* p = tmp;
while(l1 && l2)
{
if(l1->val < l2->val)
{
tmp->next = l1;
l1 = l1->next;
tmp = tmp->next;
}
else
{
tmp->next = l2;
l2 = l2->next;
tmp = tmp->next;
}
}
tmp->next = l1 ? l1 : l2;
return p->next;
}