Merge two ordered lists

package cn.edu.neu.leetcode.linked_list;

/ * * *@author32098 * /
public class MergeLinkedList {
    public static ListNode mergeTwoLists(ListNode a, ListNode b) {
        ListNode ans  = new ListNode();
        ListNode tmp = ans;
        while(a! =null&& b! =null) {if(a.val<b.val){
                tmp.val = a.val;
                a = a.next;
            }else{
                tmp.val = b.val;
                b = b.next;
            }
            tmp.next = new ListNode();
            tmp = tmp.next;
        }
        if(a==null&& b! =null){
            tmp.val = b.val;
            tmp.next = b.next;
        }else if(a ! =null){
            tmp.val = a.val;
            tmp.next = a.next;
        }
        return ans;

        // The official solution is better, save within the province
// ListNode ans = new ListNode(-1);
// ListNode tmp = ans;
// while (a! =null && b! =null) {
// if (a.val < b.val) {
// tmp.next = a;
// a = a.next;
// } else {
// tmp.next = b;
// b = b.next;
/ /}
// tmp = tmp.next;
/ /}
// tmp.next = a==null? b:a;
// return ans.next;
    }

    public static void main(String[] args) {
        int[] nums1 = new int[] {1.2.4};
        int[] nums2 = new int[] {1.3.4};
        ListNode nodeA = new ListNode(-1);
        ListNode nodeATmp = nodeA;
        ListNode nodeB = new ListNode(-1);
        ListNode nodeBTmp = nodeB;
        for (int i : nums1) {
            nodeATmp.next = new ListNode(i);
            nodeATmp = nodeATmp.next;
        }
        for (int i : nums2) {
            nodeBTmp.next = newListNode(i); nodeBTmp = nodeBTmp.next; } mergeTwoLists(nodeA.next, nodeB.next); }}Copy the code

Merge two ordered arrays

package cn.edu.neu.leetcode.normal;

/ * * *@author32098 * /
public class MergeSortedArray {
    // The code is too long compared to the official solution
    public static void merge(int[] nums1, int m, int[] nums2, int n) {
        int ind = m+n-1;
        int i = m-1;
        int j = n-1;
        while (ind>=0) {if(i<0 || j<0) {break;
            }
            if(nums1[i]>nums2[j]){
                nums1[ind] = nums1[i];
                i--;
            }else {
                nums1[ind] = nums2[j];
                j--;
            }
            ind--;
        }
        if(i>=0) {for(int k=i; k>=0; k--){ nums1[ind] = nums1[k]; ind--; }}if(j>=0) {for(int k=j; k>=0; k--){ nums1[ind] = nums2[k]; ind--; }}}public static void main(String[] args) {
        merge(new int[] {1.2.3.0.0.0}, 3.new int[] {2.5.6}, 3); }}Copy the code