算法描述:
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。
思路:
1. 兩條鏈表list1+list21分別單調遞增;
2. 選擇較小的鏈表頭作爲合併後的頭結點;
3. 再兩兩進行比較,知道兩節點大小關係反轉;
4. 時間複雜度O(n),空間複雜度O(1);
5. helper1程序看起來簡單,但其中的每個節點要比較兩次,不建議使用,建議helper2;
6. helper3通過牛客網上的test case,但是不能通過這裏的case,wrong。放這裏供參考;
7. 這裏的程序copy下來完全可以跑;
public class Main {
public static void main(String[] args) {
ListNode list1 = new ListNode(1), list2 = new ListNode(2), list3 = new ListNode(3), list4 = new ListNode(7),
list5 = new ListNode(9);
list1.next = list2;
list2.next = list3;
list3.next = list4;
list4.next = list5;
ListNode head = list1;
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println(" ");
ListNode list21 = new ListNode(0), list22 = new ListNode(4), list23 = new ListNode(5), list24 = new ListNode(6),
list25 = new ListNode(10);
list21.next = list22;
list22.next = list23;
list23.next = list24;
list24.next = list25;
head = list21;
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println(" ");
head = Merge(list1, list21);
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println(" ");
}
public static ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null)
return list2;
if (list2 == null)
return list1;
if (list1.val < list2.val)
return helper1(list1, list2);
return helper1(list2, list1);
}
public static ListNode helper1(ListNode head1, ListNode head2) {
ListNode head = head1, next = null;
while (head1 != null && head2 != null) {
if (head1.val <= head2.val) {
if (head1.next != null && head1.next.val <= head2.val) {
head1 = head1.next;
continue;
}
next = head1.next;
head1.next = head2;
head1 = next;
} else {
if (head2.next != null && head2.next.val < head1.val) {
head2 = head2.next;
continue;
}
next = head2.next;
head2.next = head1;
head2 = next;
}
}
return head;
}
public static ListNode helper2(ListNode head1, ListNode head2) {
ListNode head = head1, next = null;
while (head1 != null && head2 != null) {
if (head1.val <= head2.val) {
while (head1.next != null && head2 != null) {
if (head1.next.val <= head2.val) {
head1 = head1.next;
} else
break;
}
next = head1.next;
head1.next = head2;
head1 = next;
} else {
while (head1 != null && head2.next != null) {
if (head1.val > head2.next.val) {
head2 = head2.next;
} else
break;
}
next = head2.next;
head2.next = head1;
head2 = next;
}
}
return head;
}
public static ListNode helper3(ListNode head1, ListNode head2) {
ListNode head = head1, next1 = null, next2 = null;
while (head1 != null && head2 != null) {
if (head1.val <= head2.val) {
next1 = head1.next;
head1.next = head2;
head1 = next1;
} else {
next2 = head2.next;
head2.next = head1;
head2 = next2;
}
}
return head;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}