题目:
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
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 if (l1 == null) return l2; 12 else if (l2 == null) return l1; 13 14 ListNode head = new ListNode(0); 15 ListNode current = head; 16 17 while(l1 != null && l2 != null) { 18 if (l1.val < l2.val) { 19 current.next = l1; 20 l1 = l1.next; 21 } else { 22 current.next = l2; 23 l2 = l2.next; 24 } 25 current = current.next; 26 } 27 if (l1 != null) current.next = l1; 28 else current.next = l2; 29 30 return head.next; 31 } 32 }