题目:
Merge two sorted linked lists and return it as a new list.
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.
思路:
有递归非递归两种解法。非递归解法的思路是维护两个指针对应两个链表,以一条链表为基准,比如说l1, 那么如果l1当期那的元素比较小,那么直接移动l1即可,否则将l2当前的元素插入到l1当前元素的前面。算法时间复杂度是O(m+n),m和n分别是两条链表的长度,空间复杂度是O(1)
链表结点结构:
class ListNode{
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
递归解法:
public ListNode mergeTwoSortedLists(ListNode l1, ListNode l2){
if(l1 == null)
return l2;
if(l2 == null)
return l1;
ListNode mergedHead = null;
if(l1.val < l2.val){
mergedHead = l1;
mergedHead.next = mergeTwoSortedLists(l1.next, l2);
}else{
mergedHead = l2;
mergedHead.next = mergeTwoSortedLists(l1, l2.next);
}
return mergedHead;
}
非递归解法:
public ListNode mergeTwoSortedLists(ListNode l1, ListNode l2){
ListNode helper = new ListNode(0);
ListNode pre = helper;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
pre.next = l1;
l1 = l1.next;
pre = pre.next;
}else{
pre.next = l2;
l2 = l2.next;
pre = pre.next;
}
}
if(l2 != null){
pre.next = l2;
}
if(l1 != null){
pre.next = l1;
}
return helper.next;
}
测试代码:
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(3);
ListNode n3 = new ListNode(5);
n1.next = n2;
n2.next = n3;
ListNode m1 = new ListNode(2);
ListNode m2 = new ListNode(4);
ListNode m3 = new ListNode(6);
m1.next = m2;
m2.next = m3;
ListNode head = mergeTwoSortedLists(n1, m1);
while(head != null){
System.out.print(head.val + " ");
head = head.next;
}
}