leetcode解题方案--021--Merge Two Sorted Lists

来源:互联网 发布:在线家教平台知乎 编辑:程序博客网 时间:2024/06/02 01:14

题目

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

两个有序链表的合并。
还有一个更有意思的题是考虑进位的

第二种方法用了递归,时间更优。

public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {        ListNode ans = new ListNode(0);        ListNode header = ans;        while (l1 != null && l2 != null) {            if (l1.val > l2.val) {                ans.next = l2;                l2 = l2.next;            } else {                ans.next = l1;                l1 = l1.next;            }            ans = ans.next;        }        if (l1 == null) {            ans.next = l2;        } else {            ans.next = l1;        }        return header.next;    }    public ListNode mergeTwoLists0(ListNode l1, ListNode l2) {        if (l1 == null) {            return l2;        }        if (l2 == null) {            return l1;        }        ListNode head = null;        if (l1.val < l2.val) {            head = l1;            head.next = mergeTwoLists(l1.next, l2);        }        else {            head = l2;            head.next = mergeTwoLists(l1, l2.next);        }        return head;    }
原创粉丝点击