一、题目
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入: 1->2->4, 1->3->4
输出: 1->1->2->3->4->4
二、思路
- 参数非空判断。在进行合并之前要对参数进行非空判断,主要分为以下三种情况:1、l1为空且l2为空;2、l1为空而l2不为空;3、l1不为空而l2为空。
- 需要定义一个头结点head,用来指向合并链表的头位置。该过程需要单独在开始的时候进行。
- 对l1与l2进行遍历,取其中的较小值用来建立合并链表的下一个节点。
- 如果l1或者l2中某一个为空,则直接将另一个的所有结点添加到合并链表后面。
- 最后返回头结点。
三、代码
public class Q021_mergeTwoLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null ) return null;
if(l1 == null && l2 != null ) return l2;
if(l1 != null && l2 == null ) return l1;
ListNode l3 = new ListNode(0);
ListNode head;
if(l1.val > l2.val){
l3 = new ListNode(l2.val);
head = l3;
l2 = l2.next;
}
else{
l3 = new ListNode(l1.val);
head = l3;
l1 = l1.next;
}
while(l1 != null && l2 != null){
if(l1.val > l2.val){
l3.next = new ListNode(l2.val);
l3 = l3.next;
l2 = l2.next;
}
else{
l3.next = new ListNode(l1.val);
l3 = l3.next;
l1 = l1.next;
}
}
while(l1 != null) {
l3.next = new ListNode(l1.val);
l3 = l3.next;
l1 = l1.next;
}
while(l2 != null) {
l3.next = new ListNode(l2.val);
l3 = l3.next;
l2 = l2.next;
}
return head;
}
}