美文网首页
Merge Two Sorted Lists

Merge Two Sorted Lists

作者: 小明今晚加班 | 来源:发表于2019-02-19 20:42 被阅读3次
    题目描述

    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

    分析:改题目应该叫合并两个有序的链表,感觉这样才更准确一点。我们的初始想法无非就是再另新建一个链表,然后比大小,存入即可。
    首先定义链表:
    public class ListNode {
        int val;
        ListNode next;
    
        ListNode(int x) {
            val = x;
        }
    }
    ------------------------------------------------
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(-1);  //这个用-1或者其他值初始化没有关系的。
            ListNode cur = dummy;
    
            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;
            }
            cur.next = (l1 != null) ? l1 : l2;
            return dummy.next;    //之所以是返回dummy.next是因为我们最初创建了一个节点,值为-1,所以呢这里要返回dummy.next.
        }
    
    还有使用递归的方法如下:
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
            if (l1 == null || l2 == null) {
                return l1 == null ? l2 : l1;
            }
    
            if (l1.val < l2.val) {
                l1.next = mergeTwoLists2(l1.next, l2);
                return l1;
            } else {
                l2.next = mergeTwoLists2(l1, l2.next);
                return l2;
            }
        }
    

    相关文章

      网友评论

          本文标题:Merge Two Sorted Lists

          本文链接:https://www.haomeiwen.com/subject/utfqyqtx.html