算法思路
1. 迭代算法
类似于归并排序算法中的归并操作,比较友好的是题目给的两个链表已经是排好序的,因此我们直接跳过分治的部分,直接对两条链表进行归并。归并时我们利用两个指针分别指向两个链表的头结点,每次找到两个指针中值较小的结点,然后依次串联起来,同时不断移动指针,直到两个指针都指向了空。
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) {
auto dummy = new ListNode(-1);
auto cur = dummy;
while(l1 && l2)
{
if(l1 -> val < l2 -> val) cur = cur -> next = l1, l1 = l1 -> next;
else cur = cur -> next = l2, l2 = l2 -> next;
}
while(l1) cur = cur -> next = l1, l1 = l1 -> next;
while(l2) cur = cur -> next = l2, l2 = l2 -> next;
return dummy -> next;
}
};
2. 递归算法
和迭代算法思路相近,也是利用两个指针,找到两个指针中值更小的结点,将指针指向的剩下两个链表进行归并,并将结果链表接到值更小的结点后面。
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) {
if(l1 == NULL) return l2;
else if(l2 == NULL) return l1;
else if(l1 -> val < l2 -> val) {
l1 -> next = mergeTwoLists(l1 -> next, l2);
return l1;
}
else {
l2 -> next = mergeTwoLists(l1, l2 -> next);
return l2;
}
return NULL;
}
};