您的位置:首页 > 其它

Leetcode 21. Merge Two Sorted Lists

2017-02-15 05:36 363 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: