很简单的链表合并题目,新建一个节点,分别用两个指针指向两个链表,遍历两个链表,将值小的加入到新节点的尾巴中。

/*
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 (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode p1 = list1;
        ListNode p2 = list2;
        int head = 0;
        if (p1.val >= p2.val) {
            head = p2.val;
            p2 = p2.next;
        } else {
            head = p1.val;
            p1 = p1.next;
        }
        ListNode res = new ListNode(head);
        ListNode p = res;

        while (p1 != null && p2 != null) {
            if (p1.val >= p2.val) {
                p.next = p2;
                p2 = p2.next;
            } else {
                p.next = p1;
                p1 = p1.next;
            }
            p = p.next;
        }
        if (p1 != null) {
            p.next = p1;
        }
        if (p2 != null) {
            p.next = p2;
        }
        return res;
    }
}