您的位置:首页 > 其它

21. Merge Two Sorted Lists

2016-06-08 10:28 381 查看
题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

链接: http://leetcode.com/problems/merge-two-sorted-lists/

一刷,还是需要细心

class Solution(object):
def mergeTwoLists(self, l1, l2):
dummy_node = ListNode(0)
current = dummy_node

while l1 and l2:
if l1.val <= l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
current.next = l1 if l1 else l2
return dummy_node.next


2/11/2017, Java

ListNode current必须初始化?

最后需要判断还有剩余的list

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
else if (l2 == null) return l1;

ListNode head = new ListNode(0);
ListNode current = head;

while(l1 != null && l2 != null) {
if (l1.val < l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
if (l1 != null) current.next = l1;
else current.next = l2;

return head.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: