传统的都是再建一个新链表,但是这样子占用空间太大了
我就想着能否有一个在原来两条链表的基础上进行操作的方法
就写了这个解法,leetcode上的速度内存分析如下:
执行用时 : 2 ms , 在所有 Java 提交中击败了95.47%的用户
内存消耗 : 34.7 MB, 在所有 Java 提交中击败了97.09%的用户
直接上代码:
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode before = null;
ListNode head = null;
ListNode another = null;
ListNode result = null;
if(l1.val <= l2.val) {
head = l1;
result = head;
before = head;
another = l2;
head = head.next;
}else{
head = l2;
result = head;
before = head;
another = l1;
head = head.next;
}
//todo: 用head.next 或者another.next 来进行判断即可。
while(head != null && another != null){
if(head.val <= another.val){
before.next = head;
head = head.next;
before = before.next;
}else{
before.next = another;
another = another.next;
before = before.next;
}
}
if(head != null && another == null) {
before.next = head;
}
if(head == null && another != null) {
before.next = another;
}
return result;
}