题目描述:LeetCode原题地址
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.
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解法一: 用最直接的思路,将两个链表l1
和l2
直接从头到尾比较。即两个链表开始都指向头结点,进行比较,如果l1 -> val <= l2 -> val
,则将l1
的这个结点链接到新链表中,再使l1
指向下一个结点继续比较;同理如果l1 -> val > l2 -> val
,则将l2
的结点放到新链表中,l2
指向下一个结点。最后将某一个链表中的所有结点都链接到新链表以后,将另一个链表剩下的所有结点都直接放到新链表最后,详见代码。
代码一:
/**
* 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 *merge = new ListNode(0);
ListNode *head = merge;
//当l1和l2都不为空时继续合并
while(l1 && l2){
//l1指向的结点值小于l2指向的结点值时,将l1拼接到merge后,l1指向下一个结点
if(l1 -> val <= l2 -> val){
head -> next = l1;
l1 = l1 -> next;
}else{ //否则(即l2的结点值小于l1),将l2拼接到merge后,l2指向下一个结点
head ->next = l2;
l2 = l2 -> next;
}
head = head -> next;
}
//l1或l2已经遍历完时,将未遍历完的直接拼接到merge链表的结尾
head -> next = l1 ? l1 : l2;
return merge -> next;
}
};
解法二: 在LeetCode评论中看到的用递归实现的方法,觉得很惊艳,学习一下,以下代码来源于评论区。
代码二:
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l2->next, l1);
return l2;
}
}
};