Leetcode 21. Merge Two Sorted Lists

来源:互联网 发布:深夜解莫软件 编辑:程序博客网 时间:2024/06/07 07:08

Non-recursive solution.

public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        ListNode head = new ListNode(0);        ListNode last = head;                while (l1 != null && l2 != null) {            if (l1.val < l2.val) {                last.next = l1;                l1 = l1.next;            } else {                last.next = l2;                l2 = l2.next;            }            last = last.next;        }                // append l2 to the merged list        if (l1 == null) {            last.next = l2;        } else {            last.next = l1;        }                return head.next;    }}
Recursive solution.

public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if (l1 == null) {            return l2;        }                if (l2 == null) {            return l1;        }                ListNode head;        if (l1.val < l2.val) {            head = l1;            head.next = mergeTwoLists(l1.next, l2);        } else {            head = l2;            head.next = mergeTwoLists(l1, l2.next);        }                return head;    }}



0 0
原创粉丝点击