描述

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

 

解析

节点依次比较,指针移动。类似归并的merge方法,思路一样。

 

代码

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if (null == list1 && null == list2) {
            return null;
        } else if (null == list1) {
            return list2;
        } else if (null == list2) {
            return list1;
        }
        //设置一个头节点
        ListNode newListNode = new ListNode(0);
        ListNode root = newListNode;
        while (null != list1 && null != list2) {
            if (list1.val < list2.val) {
                newListNode.next = list1;
                newListNode = list1;
                list1 = list1.next;
            } else {
                newListNode.next = list2;
                newListNode = list2;
                list2 = list2.next;
            }
        }
        if (null != list1) {
            newListNode.next = list1;
        }
        if (null != list2) {
            newListNode.next = list2;
        }
        return root.next;
    }
}

 

posted on 2019-04-25 15:19  反光的小鱼儿  阅读(125)  评论(0编辑  收藏  举报