您的位置:首页 > 其它

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