Description
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.
分析
合并两个有序的链表,和归并排序中,合并两个有序的数组很相似。回顾一下归并排序的合并过程,创建一个输出数组,其大小等于两个有序数组大小之和,其一指针指向数组第一个元素,各有一个指针指向两个有序的数组第一个元素,比较两个指针指向的元素,将较小的元素放置输出数组中,然后移动指向较小元素的指针和移动指向输出数组的指针。重复上述过程,直至两个数组归并至输出数组。每次都将较小的元素放至输出数组,可以保证输出数组有序。
现在来看两个链表的merge。先保存一个fakeHead,使其的值为-1。比较两个链表头指针指向的节点,将较小的节点放置输出链表末尾。重复至两个链表的节点为空。然后删除fakeHead。返回。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode opList;
if(l1==null){
opList=l2;//if l1==null return l2
}else if(l2==null){
opList=l1;//if l2==null return l1
}else{
opList=new ListNode(-1);//temperoliy haed
ListNode current=opList;
while(true){
if(l1.val<l2.val){
current.next=l1;
l1=l1.next;//move a step
}else{
current.next=l2;
l2=l2.next;//move a step
}
current=current.next;//current move a step
if(l1==null){//final merge if one of them is empty
current.next=l2;
break;
}else if(l2==null){
current.next=l1;
break;
}
}
//merge
opList=opList.next;//remove -1 tmp head
}
return opList;//if both list is null, return null
}
}
可以使用递归写出更简洁的代码。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){return l2;}
if(l2==null){return l1;}
ListNode mergeHead=null;
if(l1.val<l2.val){
mergeHead=l1;
mergeHead.next=mergeTwoLists(l1.next,l2);//find next
}else{
mergeHead=l2;
mergeHead.next=mergeTwoLists(l1,l2.next);//find next
}
return mergeHead;
}
}