【Leetcode】Merge Two Sorted Lists (2 lists)
2014-10-25 09:01
513 查看
题目要求合并两个排好序的链表,这道题和add 2 number 思路比较类似,都是构造一个helper,然后把满足条件的NODE一个个往上添加
这道题注意的是指针的移动。不要忘记移动runner指针。
代码如下
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode helper = new ListNode(0);
ListNode runner = helper;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
runner.next = l1;
runner = runner.next;
l1 = l1.next;
} else {
runner.next = l2;
runner = runner.next;
l2 = l2.next;
}
}
if (l1 != null)
runner.next = l1;
if (l2 != null)
runner.next = l2;
return helper.next;
}
这道题注意的是指针的移动。不要忘记移动runner指针。
代码如下
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode helper = new ListNode(0);
ListNode runner = helper;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
runner.next = l1;
runner = runner.next;
l1 = l1.next;
} else {
runner.next = l2;
runner = runner.next;
l2 = l2.next;
}
}
if (l1 != null)
runner.next = l1;
if (l2 != null)
runner.next = l2;
return helper.next;
}
相关文章推荐
- LeetCode 21. Merge Two Sorted Lists
- leetcode - Merge Two Sorted Lists
- LeetCode 21 - Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists
- LeetCode_Merge Two Sorted Lists
- leetcode Merge Two Sorted Lists
- [面试真题] LeetCode:Merge Two Sorted Lists
- LeetCode 之Merge Two Sorted Lists
- (Java)LeetCode-21. Merge Two Sorted Lists
- LeetCode——Merge Two Sorted Lists
- Merge Two Sorted Lists--LeetCode
- LeetCode ---Merge Two Sorted Lists
- LeetCode--Merge Two Sorted Lists(合并两个有序链表)Python
- LeetCode:Merge Two Sorted Lists
- leetcode--Merge Two Sorted Lists
- Leetcode Problem.21—Merge Two Sorted Lists
- leetcode Merge Two Sorted Lists(Java)
- [leetcode]Merge Two Sorted Lists
- leetcode Merge Two Sorted Lists
- [LeetCode] 21 - Merge Two Sorted Lists