MergeTwoSortedLists
何年後、世界を揺らす風が吹き、あなたの体が軽く、その陣風、二人は別れて、しかし、心は永遠に離れない。
前言:
最近老婆打算内部转岗,和之前岗位上的一个同事合不太来,祝愿她顺利;同时她妹妹又闹别扭,不想去上学,怎么说也不听,像极了之前钻牛角尖的我,头疼。。。现在看到各个弟弟妹妹们浪费自己的青春觉得好可惜,可能同时也可惜自己当时还不够努力吧。不过一切都只有向前看,种一棵树最好的时间是十年前,其次是现在?
package list;
/**
* @author BlackSugar
* @date 2019/4/16
* Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
* <p>
* Example:
* <p>
* Input: 1->2->4, 1->3->4
* Output: 1->1->2->3->4->4
*/
public class MergeTwoSortedLists {
/**
* 合并两个递增链表
* 思路:创建一条新链表,以l1、l2小的为节点,小节点的链表获取后一个节点再比较,若其中一条链表结束,则直接将另一条链表剩余节点加入
* l1:123;l2:234--->122334
* 一般思路:新建一条链表,以l1、l2小的节点的值创建新节点,直到l1、l2都为空
*
* @param l1
* @param l2
* @return
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode re = null, listNode = null;
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
do {
if (l1.val < l2.val) {
if (listNode == null) {
re = listNode = l1;
} else {
listNode = listNode.next = l1;
}
l1 = l1.next;
} else {
if (listNode == null) {
re = listNode = l2;
} else {
listNode = listNode.next = l2;
}
l2 = l2.next;
}
} while (l1 != null && l2 != null);
if (l1 == null) {
listNode.next = l2;
}
if (l2 == null) {
listNode.next = l1;
}
return re;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
l1.next(3).next(4);
ListNode l2 = new ListNode(2);
l2.next(4).next(8);
ListNode re = new MergeTwoSortedLists().mergeTwoLists(l1, l2);
while (re != null) {
System.out.print(re.val);
re = re.next;
}
System.out.println();
}
}
总结:
这道题大家一般的思路是创一个新节点,然后依次比较两条list,找到小的值插入新节点的next并移动相应list的指针,直到两条list都到尾节点。我们可以进行一点点优化,先比较两个list的头节点,取小的那个为新的头(这样可以少new一个节点对象),然后遍历直到其中一条节点到尾节点即可,跳出循环后直接指向剩下的list的后半部分(这样少遍历一部分链表)。
1、时间复杂度O(n)
2、空间复杂度O(1)