题目来源:
https://leetcode.com/problems/merge-two-sorted-lists/
题意分析:
题目给出两个排好序的链表,将这两个链表整合成一个新的有序的链表。
题目思路:
这道题目很简单,首先构造一个新的链表,比较两个链表的指针指向的节点的值大小,将值较少的节点放到新链表中,并将指针位置往后移动一位,直到某个链表为空之后,把剩下的链表全部放到新的链表中就可以了。时间复杂度是(O(m+n))
代码(python):
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution(object): 8 def mergeTwoLists(self, l1, l2): 9 """ 10 :type l1: ListNode 11 :type l2: ListNode 12 :rtype: ListNode 13 """ 14 ans = ListNode(0) 15 tmp = ans 16 if l1 == None and l2 == None: 17 return None 18 while l1 !=None or l2 != None: 19 if l1 == None: 20 while l2 != None: 21 tmp.val = l2.val 22 l2 = l2.next 23 if l2 == None: 24 break 25 tmp.next = ListNode(0) 26 tmp = tmp.next 27 break 28 if l2 == None: 29 while l1 != None: 30 tmp.val = l1.val 31 l1 = l1.next 32 if l1 == None: 33 break 34 tmp.next = ListNode(0) 35 tmp = tmp.next 36 break 37 if l1.val <= l2.val: 38 tmp.val = l1.val 39 l1 = l1.next 40 else: 41 tmp.val = l2.val 42 l2 = l2.next 43 tmp.next = ListNode(0) 44 tmp = tmp.next 45 return ans
转载请注明出处:http://www.cnblogs.com/chruny/p/4872779.html