021.Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

解答:
定义节点:

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

思路:比较两个链表的头结点大小,小的节点加入新链表里面,最后剩余的一个链表全部加入新链表里面。
Attention:leetcode上面的链表头结点是存储值的。

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        //合并链表,比较大小  首先你确实需要一个头结点来存储
        // 还有实时指向尾结点的指针
        ListNode head = new ListNode(0);
        ListNode temp = head;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                temp.next = l1;
                l1 = l1.next;
            } else {
                temp.next = l2;
                l2 = l2.next;
            }
            temp = temp.next;
        }
        if (l1 != null) {
            temp.next = l1;
        }
        if (l2 != null) {
            temp.next = l2;
        }
        return head.next;
    }
}
原文地址:https://www.cnblogs.com/d9e84208/p/12006919.html