【LeetCode】21. Merge Two Sorted Lists - Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84332981

1. 题目描述:

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

2. 思路分析:

题目的意思是合并2个有序的链表。

思路是用2个指针分别指向2个链表,比较2个节点,将较小的节点放入结果链表中并且指针后移。

3. Java代码:

源代码见我GiHub主页

代码:

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null) {
        return l2;
    }
    if (l2 == null) {
        return l1;
    }

    ListNode result = new ListNode(0);
    ListNode cur = result;
    while (l1 != null && l2 != null) {
        if (l1.val < l2.val) {
            cur.next = l1;
            l1 = l1.next;
        } else {
            cur.next = l2;
            l2 = l2.next;
        }
        cur = cur.next;
    }
    if (l1 != null) {
        cur.next = l1;
    }
    if (l2 != null) {
        cur.next = l2;
    }

    return result.next;
}   

猜你喜欢

转载自blog.csdn.net/xiaoguaihai/article/details/84332981
今日推荐