问题
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路
思路较为简单,难度在与对两个链表的各种边界情况的处理。
代码
//import utils.delwithNodeList;
//import utils.ListNode;
import Utils.*;
public class _21MergeTwoSortedLists{
public ListNode mergeTwoLists(ListNode L1,ListNode L2){
ListNode head = null;
ListNode tmp = null;
while(L1!=null||L2!=null){
if(L1!=null&&L2!=null){
if(L1.val>=L2.val){
if(tmp==null){
tmp = L2;
head = tmp;
L2 = L2.next;
}else{
tmp.next = L2;
tmp = tmp.next;
L2 = L2.next;
}
}else{
if(tmp==null){
tmp = L1;
head = tmp;
L1 = L1.next;
}else{
tmp.next = L1;
tmp = tmp.next;
L1 = L1.next;
}
}
}else if(L1!=null&&L2==null){
if(tmp==null){
tmp = L1;
head = tmp;
return head;
}else{
tmp.next = L1;
return head;
}
}else{
if(tmp==null){
tmp = L2;
head = tmp;
return head;
}else{
tmp.next = L2;
return head;
}
}
}
return head;
}
private ListNode addNode(ListNode head,ListNode tmp,ListNode L){
if(tmp==null){
tmp = L;
head = tmp;
tmp = tmp.next;
L = L.next;
}else{
tmp = L;
tmp = tmp.next;
L = L.next;
}
System.out.println("hello1");
//System.out.println(delwithListNode.readList(L2));
System.out.println(delwithListNode.readList(head));
System.out.println("hello1");
return L;
}
public static void main(String[] arg){
//ListNode L1 = delwithListNode.getNodelist(new int[]{1,2,4});
//ListNode L2 = delwithListNode.getNodelist(new int[]{1,3,4});
ListNode L1 = delwithListNode.getNodelist(new int[]{1,3});
ListNode L2 = delwithListNode.getNodelist(new int[]{5,7});
String list1 = delwithListNode.readList(L1);
String list2 = delwithListNode.readList(L2);
System.out.println(list1);
System.out.println(list2);
_21MergeTwoSortedLists MergeTwoSortedLists = new _21MergeTwoSortedLists();
ListNode L3 = MergeTwoSortedLists.mergeTwoLists(L1,L2);
String list = delwithListNode.readList(L3);
System.out.println(list);
}
}