问题描述:
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.
https://leetcode.com/problems/merge-two-sorted-lists/description/
思路分析:
完成两个已经排序的链表的值的比较,合并排序之后返回一个新的链表。使用递归的方式解决,递归的结束条件是当有一个链表没有后继元素时,返回另一个链表,比较链表的值,选择值更小的node,然后node->next 是 node->next与另一个链表当前值的比较结果。
代码:
java解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
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(l1, l2.next);
return l2;
}
}
}
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(l1,l2->next);
return l2;
}
}
};
时间复杂度:O(m+n) //m,n为l1和l2的长度
反思:对于链表知识的缺乏导致了这一题的解题很是困难。参考了leetcode上的discussion才写出了这个答案。思路很清晰,基本是抄的囧。这个方法改变了原有链表,可以维持一个新链表来解决。