![](https://www.dazhuanlan.com/webchat.jpg)
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.
![](https://Daniellau331.github.io//post/32231/photo1.PNG)
解題
這題基本上就是比一下兩個linked lists第一個node的value,拿小的(由於兩個linked list都是sorted,所以比較大家第一個node就行了),然後去造一個新的linked lists。
代碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class (object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ result = dummy = ListNode(None) while l1 and l2: if l1.val<l2.val: dummy.next = l1 l1 = l1.next else: dummy.next = l2 l2 = l2.next dummy = dummy.next dummy.next = l1 or l2 return result.next
|
近期评论