題目:合並兩個有序鏈表
將兩個升序鏈表合並為一個新的 升序 鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
package com.test.day6_10;
/**
* @author cosefy
* @date 2020/6/10
*/
public class MergeTwoLists {
public static void main(String[] args) {
ListNode l1 =new ListNode(1,new ListNode(3,new ListNode(4,null)));//1-3-4
ListNode l2 =new ListNode(1,new ListNode(2,new ListNode(4,null)));//1-2-4
ListNode l3 = mergerTwoLists(l1, l2);
ListNode.showList(l3);
}
ListNode類:
public class ListNode {
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
public static void showList(ListNode node) {
while (node!=null) {
System.out.print("ListNode: "+ "val="+node.val+" ");
node= node.next;
}
}
ListNode(int val, ListNode next){
this.val=val;
this.next=next;
}
}
解法:常規解法
思路:當兩個鏈表都不為空時,依次尋找最小結點,鏈接,當其中一鏈表遍歷結束,把另一鏈表的剩余部分鏈接上。
分析:最壞時間復雜度O(n+m),空間復雜度O(1)
public static ListNode mergerTwoLists(ListNode l1, ListNode l2) {
ListNode l3= new ListNode(0,null);
ListNode mark = l3;
while(l1!=null && l2!=null){
if (l1.val < l2.val) {
l3.next = l1;
l1 = l1.next;
} else {
l3.next=l2;
l2 = l2.next;
}
l3= l3.next;
}
if (l1 != null) {
l3.next=l1;
}
if (l2 != null) {
l3.next=l2;
}
return mark.next;
}
}
結果:ListNode: val=1 ListNode: val=1 ListNode: val=2 ListNode: val=3 ListNode: val=4 ListNode: val=4