题目描述:
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
例如输入:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
数据范围:
0 <= 链表长度 <= 1000
解题思路:
1.初始化一个空头结点,head3和tail同时指向这个结点。head1,head2是两个链表的头结点
2.循环进行合并。
- head1和head2都不为null时执行
- head1->val > head2->val , head3的后继结点为head1, head1向后走一步
- head2->val > head1->val , head3的后继结点为head2,head2向后走一步
- 合并剩余部分(跳出循环一定是head1后者head2遍历到最后(即为null)
- head1不为null,head3->next = head1
- head2不为null,head3->next = head2
- 返回tail->next
AC代码(c++)
/**
* 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) {
ListNode * head1 = l1;
ListNode * head2 = l2;
ListNode * head3 = new ListNode();
ListNode * tail = head3;
while(head1 && head2){
if(head1->val <= head2->val){
head3->next = head1;
head1=head1->next;
}else{
head3->next = head2;
head2=head2->next;
}
head3 = head3->next;
}
if(head1){
head3->next = head1;
}
if(head2){
head3->next = head2;
}
return tail->next;
}
};