[LeetCode] NO.21 Merge Two Sorted Lists
[题目] 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.
[题目解析] 题目需要合并两个有序的链表,这是归并排序的中间步骤,数组和链表的合并如下。
public int[] mergeArray(int[] arr1, int[] arr2){
int len1 = arr1.length;
int len2 = arr2.length;
int[] ret = new int[len1+len2];
int i=0,j=0,idx=0;
while(i < len1 && j < len2){
if(arr1[i] < arr2[j]){
ret[idx++] = arr1[i];
i++;
}else{
ret[idx++] = arr2[j];
j++;
}
}
while(i < len1){
ret[idx++] = arr1[i];
i++;
}
while(j < len2){
ret[idx++] = arr2[j];
j++;
}
return ret;
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(null == l1) return l2;
if(null == l2) return l1;
ListNode ret = new ListNode(0);
ListNode head = ret;
while(null != l1 && null != l2){
if(l1.val < l2.val){
ret.next = l1;
l1 = l1.next;
}else{
ret.next = l2;
l2 = l2.next;
}
ret = ret.next;
}
while(null != l1){
ret.next = l1;
l1 = l1.next;
ret = ret.next;
}
while(null != l2){
ret.next = l2;
l2 = l2.next;
ret = ret.next;
}
return head.next;
}
}

浙公网安备 33010602011771号