【Description】
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
【Idea】
定义两个指针,一个作头指针,另一个作尾指针
对两个链表同时比较头元素,将较小的节点加入新链表中,同时对应链表的头指针后移一位;
最后考虑两个链表不等长,或者其中一个链表有更多小于另一个链表值的节点数量的情况,将剩余未遍历到的子链表直接加入(给定链表分别有序)
【Solution】
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
new_head = ListNode(0)
prev = new_head
while l1 and l2:
if l1.val >= l2.val:
prev.next = l2
prev = prev.next
l2 = l2.next
elif l2.val > l1.val:
prev.next = l1
prev = prev.next
l1 = l1.next
if l1:
prev.next = l1
if l2:
prev.next = l2
return new_head.next
网友评论