输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
本题在力扣上给定的标签是简单题,这是因为合并的是两个有序链表,既然有序,那我们只需要将两个链表开始遍历,将小的一方放入新链表,指针后移即可。当有一个链表为空时,就将不为空的链表依次遍历到新链表上,便完成了本题。跟着这个思路,我们可以很容易的写出本题代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode h = head;
// ListNode a = new ListNode(0);
if(l1 == null && l2 == null){
return null;
}
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
while(l1 != null && l2 != null){
if(l1.val > l2.val){
ListNode a = new ListNode(l2.val);
head.next = a;
head = head.next;
l2 = l2.next;
}else{
// a.val = l1.val;
ListNode a = new ListNode(l1.val);
head.next = a;
head = head.next;
l1 = l1.next;
}
}
if(l1 == null){
while(l2 != null){
ListNode a = new ListNode(l2.val);
// a.val = l2.val;
head.next = a;
head = head.next;
l2 = l2.next;
}
}
if(l2 == null){
while(l1 != null){
ListNode a = new ListNode(l1.val);
// a.val = l1.val;
head.next = a;
head = head.next;
l1 = l1.next;
}
}
return h.next;
}
}
上面代码初看可以觉得没什么不妥的,但是你细看就会发现其实有很多冗余的代码,也有很多可以省去的代码,比如说在两个链表比较大小插入新链表时,无论是哪个链表的值要插入新链表,新链表的指针都得下移一位,所以我们可以把操作新链表的部分拿到判断逻辑外来处理,减少代码容易:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode h = head;
// ListNode a = new ListNode(0);
if(l1 == null && l2 == null){
return null;
}
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
while(l1 != null && l2 != null){
ListNode a;
if(l1.val > l2.val){
a = new ListNode(l2.val);
l2 = l2.next;
}else{
a = new ListNode(l1.val);
l1 = l1.next;
}
head.next = a;
head = head.next;
}
if(l1 == null){
ListNode a;
while(l2 != null){
a = new ListNode(l2.val);
head.next = a;
head = head.next;
l2 = l2.next;
}
}
if(l2 == null){
ListNode a;
while(l1 != null){
a = new ListNode(l1.val);
head.next = a;
head = head.next;
l1 = l1.next;
}
}
return h.next;
}
}
相比较于刚刚的代码,是不是看起来规整了不少,但是这仍然有可以删减的部分,当两个链表有一个为空时,我们就可以直接将不为空的链表当前节点直接连在新链表的后面即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode h = head;
// ListNode a = new ListNode(0);
if(l1 == null && l2 == null){
return null;
}
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
while(l1 != null && l2 != null){
ListNode a;
if(l1.val > l2.val){
a = new ListNode(l2.val);
l2 = l2.next;
}else{
a = new ListNode(l1.val);
l1 = l1.next;
}
head.next = a;
head = head.next;
}
if(l1 == null){
head.next = l2;
}
if(l2 == null){
head.next = l1;
}
return h.next;
}
}
至此,我们将该逻辑的代码已经进行了最终的优化,看起来是不是就要整洁的多了。