25. 合并两个排序的链表

题目

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
例如:
链表1:1->3->5->7
链表2:2->4->6->8
合并后:1->2->3->4->5->6->7->8

思路

假如List1中的头节点是小于List2中的,那么新的链表的头节点必将是List1的头节点,同理对List2也一样,那么在比较完头节点之后,再将List1中的下一个节点再与List2中的头节点比较,同样谁小谁进入新链表,然后再比较,直到两个链表比较完,故可用非递归或递归两种方式来做。

实现

  1. 非递归,设立虚拟头结点
public static class ListNode {
    public int val;
    public ListNode next = null;
    public ListNode(int val) {
        this.val = val;
    }
}

public static ListNode Merge(ListNode list1,ListNode list2) {
//判断空的情况
    if(list1 == null)
        return list2;
    if(list2 == null)
        return list1;
//为合并后的新链表设立虚拟头结点,
    ListNode dummyHead = new ListNode(0);
    ListNode cur = dummyHead ;
//比较大小,合并至新链表
    while(list1 != null && list2 != null) {
        if(list1.val > list2.val) {
            cur.next = list2;
            list2 = list2.next;
            cur = cur.next;
        }
        else {
            cur.next = list1;
            list1 = list1.next;
            cur = cur.next;
        }
    }
//此时至少有一个链表已经全部被合并至新链表
    if(list1 != null)
        cur.next = list1;
    else if(list2 != null)
        cur.next = list2;

    return dummyHead.next;
}

  1. 递归方法
public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        ListNode newHead = null;
        if(list1.val <= list2.val){
            newHead = list1;
            newHead .next = Merge(list1.next,list2);
        }else{
            newHead = list2;
            newHead .next = Merge(list1,list2.next);
        }
        return newHead ;
    }

你可能感兴趣的:(25. 合并两个排序的链表)