合并过有序数组链接在这里,思想截然不同。
中规中矩地合并。
需要注意的点
- 需要构造一个头结点,并保留头结点的标记。返回时需要用到。
- 头结点构造的时候head不能赋值为null,为null的话,head.next就会报空指针异常了
- 处理剩余节点的时候,不需要一个一个赋值了,因为这是链表,把l2或者l1指过去就行了(数组需要一个一个赋值)。
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 head = new ListNode(0);
ListNode tail = head;
while(l1 != null && l2 != null ){
if(l1.val < l2.val){
head.next = l1;
l1 = l1.next;
}else{
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
head.next = (l1 == null) ? l2 : l1;
return tail.next;
}
}