常考数据结构和算法:合并有序链表

将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的,且合并后新链表依然有序。

示例1

输入

{1},{2}

返回值

{1,2}

示例2

输入

{2},{1}

返回值

{1,2}
class ListNode {
    int val;
    ListNode next = null;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }
}


public class TestMergetList {
    public static void main(String[] args) {
        System.out.println("main...");
    }

    /**
     * @param l1 ListNode类
     * @param l2 ListNode类
     * @return ListNode类
     */
    public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
        if(null == l1){
            return l2;
        }
        if(null == l2){
            return l1;
        }

        ListNode first = l1;
        ListNode secode = l2;
        ListNode head = new ListNode(-1);
        ListNode temp = head;
        while(null!= first && null !=secode){
            if(first.val < secode.val){
                temp.next = first;
                temp = first;
                first = first.next;
            }else{
                temp.next = secode;
                temp = secode;
                secode = secode.next;
            }
        }

        if(null != first){
            temp.next = first;
        }
        if(null != secode){
            temp.next = secode;
        }

        return head.next;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37564426/article/details/113785117