165. 合并两个排序链表

165. 合并两个排序链表

中文English

将两个排序链表合并为一个新的排序链表

样例

样例 1:
	输入: list1 = null, list2 = 0->3->3->null
	输出: 0->3->3->null


样例2:
	输入:  list1 =  1->3->8->11->15->null, list2 = 2->null
	输出: 1->2->3->8->11->15->null

 
 
输入测试数据 (每行一个参数)如何理解测试数据?
"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param l1: ListNode l1 is the head of the linked list
    @param l2: ListNode l2 is the head of the linked list
    @return: ListNode head of linked list
    """
    def mergeTwoLists(self, l1, l2):
        # write your code here
        #初始化一个新的链表,循环,比较l1.val 和 l2.val的大小。最后,如果那个链表没有取完,则直接丢进来
        
        #初始化一个新的链表
        dummay = ListNode(0)
#如果不重新赋值tail尾巴的话,dummy一直在往后面链接新的节点,但是最终需要返回的是第一个节点的next,所以需要一个尾巴在后面不停的链接新节点,不停的更新指向 tail
= dummay while l1 and l2: if l1.val < l2.val: #每一个赋予一个新的节点 tail.next = ListNode(l1.val) l1 = l1.next else: tail.next = ListNode(l2.val) l2 = l2.next tail = tail.next #最后,如果还剩下l1,或者l2 if l1: tail.next = l1 else: tail.next = l2 return dummay.next
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13462200.html