合并两个排序的链表

题目描述:

  输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则

解题思路:

  两个链表都是单调递增的,故可以通过递归比较,得到排列后的新链表,下面上代码

/**
 * 合并两个排序的链表
 * 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则
 *
 * @author ihaokun
 * @date 2019/7/24 20:36
 */
public class MergeLinkedList {
    public static void main(String[] args) {
        // init test 1
        /*ListNode head1 = new ListNode(1);
        head1.next = new ListNode(2);
        head1.next.next = new ListNode(3);
        ListNode head2 = new ListNode(2);
        head2.next = new ListNode(4);*/
        // init test 2
        /*ListNode head1 = null;
        ListNode head2 = null;*/
        // init test 3
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(2);
        head1.next.next = new ListNode(3);
        ListNode head2 = new ListNode(1);
        head2.next = new ListNode(2);
        head2.next.next = new ListNode(3);
        ListNode head = merge(head1, head2);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

    static ListNode merge(ListNode list1, ListNode list2) {
        ListNode head = null;
        if (list1 != null && list2 != null) {
            if (list1.val > list2.val) {
                head = list2;
                list2 = list2.next;
            } else {
                head = list1;
                list1 = list1.next;
            }
            head.next = merge(list1, list2);
        } else {
            if (list1 != null){
                head = list1;
            } else if (list2 != null){
                head = list2;
            }
        }
        return head;
    }

    static class ListNode {
        int val;
        ListNode next = null;

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

 

posted @ 2019-07-25 20:56  AloeAndClover  阅读(150)  评论(0编辑  收藏  举报