将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的,且合并后新链表依然有序。输入{1},{2}输出{1,2}
题解:首先两个链表本身就是有序的,这样就可以用比较笨重的方法遍历每个链表的头,
将小的插入到新的链表中,循环直到有一个链表为空,把另一个直接挂到新链表的尾部,
就达到了我们想要的结果。
循环比较插入新链表
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) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode res = new ListNode(0);
ListNode cur=res;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
cur.next=l1;
l1=l1.next;
}else{
cur.next=l2;
l2=l2.next;
}
cur=cur.next;
}
//不为空链表直接连接
cur.next=l1==null?l2?l1;
return res.next;
}
}
- 通过查看上述代码发现本题还可以通过递归的方式来实现代码更加简洁。
递归方式
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) {
if(l1==null||l2==null) return l1==null?l2:l1;
ListNode resFirst =(l1.val<l2.val)?l1:l2;
resFirst.next=mergeTwoLists(resFirst.next,resFirst==l1?l2:l1);
return resFirst;
}
}