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.
給你2個排序好的單鏈表,返回一個merge的單鏈表。
鏈表數據結構:
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
2個單鏈表各設一個遊標,並設一個result節點。
對比2個遊標,並將result指向較小的那個遊標,較小的遊標再向後移一位。
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode cur1 = l1;
ListNode cur2 = l2;
ListNode head, result, temp1, temp2;
if (l1 == null && l2 == null)
return null;
if (l1 == null)
return l2;
if (l2 == null)
return l1;
head = cur1.val < cur2.val ? cur1 : cur2;
result = new ListNode(0);
while (cur1 != null & cur2 != null) {
result.next = cur1.val < cur2.val ? cur1 : cur2;
result=result.next;
if (cur1.val < cur2.val) {
cur1 = cur1.next;
} else
cur2 = cur2.next;
}
if (cur1 == null)
result.next = cur2;
if (cur2 == null)
result.next = cur1;
return head;
}