21. 合并两个有序链表

思路:

需要注意的就是指针的指向处理。
pre指针跟随l1和l2中值较小者向后顺移,每一步指向二者中的较小者,负责确立指向关系;
若l1>=l2,pre指向l2,l2向后顺移一位。否则pre指向l1,l1向后顺移。

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # 返回值链表的头指针
        prehead = ListNode(-1)
        pre = prehead
        while l1 and l2:
            if l1.val >= l2.val:
                pre.next = l2
                l2 = l2.next
            else:
                pre.next = l1
                l1 = l1.next
            pre = pre.next
        # 把未遍历到的节点接到新链表的后面
        pre.next = l1 if l1 is not None else l2
        return prehead.next
原文地址:https://www.cnblogs.com/panweiwei/p/12856989.html