题目描述:
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
思路:
两个有序字符串合并问题,谁小就把谁通过尾插法添加到一个新的链表中,直到有一个为空,把另一个剩下的链表链接到那个新的链表上。
我的代码:
def mergeTwoLists(l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = l = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
l.next = l1
l1 = l1.next
else:
l.next = l2
l2 = l2.next
l = l.next
l.next = l1 or l2
return head.next
学到:
- 定义新的链表
l = ListNode(0)
- 返回一个链表的时候,如果有头节点,返回的是头节点的下一个节点:
return head.next