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;
}
}
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;
}
}
相关文章推荐
- leetcode-21. Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- Leetcode 21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- 【一天一道LeetCode】#21. Merge Two Sorted Lists
- leetcode题解-21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- 【一天一道LeetCode】#21. Merge Two Sorted Lists
- LeetCode *** 21. Merge Two Sorted Lists
- LeetCode --- 21. Merge Two Sorted Lists
- [LeetCode]21. Merge Two Sorted Lists
- [LeetCode]--21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- LeetCode - 21. Merge two sorted lists
- leetcode--21. Merge Two Sorted Lists
- [leetcode]: 21. Merge Two Sorted Lists
- [LeetCode]21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists