LeetCode算法题——21. Merge Two Sorted Lists

来源:互联网 发布:淘宝贷款怎么手动还款 编辑:程序博客网 时间:2024/06/08 05:19
题目
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.

算法思想:
比较两个已排序的链表的第一个元素,哪一个链表第一个元素小则添加到新的链表中去,并将该链表指针移向下一个元素,同理再比较,循环的终止条件是其中一个链表被遍历,之后把未遍历完的链表元素添加到新链表的后面。

PythonS算法实现如下:

# -*- coding:utf-8 -*-# Definition for singly-linked list.class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Noneclass Solution(object):    def mergeTwoLists(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        retList=None        p=retList        while l1!=None and l2!=None:            temp=None            if l1.val<l2.val:                temp=ListNode(l1.val)                l1=l1.next            else:                temp=ListNode(l2.val)                l2=l2.next            temp.next=None            if retList==None:                retList=p=temp            else:                p.next=temp;                p=p.next        while l1!=None:            temp=ListNode(l1.val)            temp.next=None            if retList==None:                retList=p=temp            else:                p.next=temp;                p=p.next            l1=l1.next        while l2!=None:            temp=ListNode(l2.val)            temp.next=None            if retList==None:                retList=p=temp            else:                p.next=temp;                p=p.next            l2=l2.next        return retList    if __name__ == '__main__':    lhead1=None    lhead2=None    p1=lhead1    p2=lhead2    data1=[1,2,4,6,9]    data2=[3,5,8]#     data1=[]#     data2=[0]    for i in data1:        q1=ListNode(i)        q1.next=None        if lhead1==None:            lhead1=p1=q1        else:            p1.next=q1            p1=p1.next    for i in data2:        q2=ListNode(i)        q2.next=None        if lhead2==None:            lhead2=p2=q2        else:            p2.next=q2            p2=p2.next    s=Solution();    res=s.mergeTwoLists(lhead1,lhead2)    while res!=None:        print(res.val)        res=res.next


0 0