将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。
方法一:递归
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
// write code here
if(l1 == null)return l2;
if(l2 == null)return l1;
ListNode pre = null;
if(l1.val<l2.val){
pre = l1;
pre.next = mergeTwoLists(l1.next,l2);
}
else{
pre = l2;
pre.next = mergeTwoLists(l1,l2.next);
}
return pre;
}
}
方法二:循环
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
// write code here
ListNode head = new ListNode(0);
ListNode pre = head;
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
pre.next = l1;
l1 = l1.next;
}
else{
pre.next = l2;
l2 = l2.next;
}
pre = pre.next;
}
if(l1 != null){
pre.next = l1;
}
if(l2 != null){
pre.next = l2;
}
return head.next;
}
}