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.
改了好久,可是明明不难的啊。
代码:
package leetcode;
import java.util.ArrayList;
public class MergeTwoLists {
public static void main(String[] args) {
MergeTwoLists m = new MergeTwoLists();
ListNode l11 = new ListNode(5);
ListNode l21 = new ListNode(1);
ListNode l22 = new ListNode(2);
ListNode l23 = new ListNode(4);
l21.next = l22;
l22.next = l23;
//ListNode l21 = new ListNode(1);
ListNode l =m.mergeTwoLists( new ListNode(2), new ListNode(1));
while(l!=null){
System.out.println(l.val);
l=l.next;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode p1 = l1,p2 = l2;
//指针指向两个列表的头,一点点加入merge 这个链表
if(l1 ==null && l2 ==null)
return null;
ListNode head = new ListNode(-1);
ListNode tar = head;
while(p1!=null && p2 !=null){
tar.val = p1.val>p2.val?p2.val:p1.val;
if(p1.val>p2.val){
tar.next = p2;
p2 = p2.next;
}else{
tar.next = p1;
p1 = p1.next;
}
tar = tar.next;
}
//如果其中一个已经加完了,将另个的剩余部分加入到merge中去
if(p1!=null){
tar.next = p1;
}
if(p2!=null){
tar.next = p2;
}
return head.next;
}
}