LeetCode Easy: 21. Merge Two Sorted Lists

一、题目

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

二、解题思路

   本题给定的两个链表是已经排好序的,首先定义一个空链表,然后从给定的两个链表的头节点开始比较,比较两个链接表的头节点,小的作为合并后链表的头结点,然后移动头指针,因为给定的两个链表都是已经排好序的,所以只需要比较两个链表的头部就行了。考虑到程序的鲁棒性,输入特殊的链表,比如空链表时,应该做出判断。                       
代码参考:http://blog.csdn.net/qq_28119401/article/details/52578096
def mergeTwoLists(l1,l2):
    if l1 is None:
        return l2
    if l2 is None:
        return l1
#定义虚表头
    dummyhead = ListNode(0)
    dummyhead.next = None
    p = dummyhead
    while l1 is not None and l2 is not None:
        if l1.val > l2.val:
            p.next = l2
            l2 = l2.next
        else:
            p.next = l1
            l1 = l1.next
        p = p.next
    if l1 is not None:
        p.next = l1
    else:
        p.next = l2
    return dummyhead.next

  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8616177.html