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.
将两个排好序的链表拼接成一个新的链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def mergeTwoLists(self, l1, l2):
if l1 == None:
return l2
if l2 == None:
return l1
if l1.val>l2.val:
temp = l2
l2 = l1
l1 = temp
l = l1
while l2 != None:
if l1.next==None:
l1.next = l2
break
if l1.next.val > l2.val:
temp = l1.next
l1.next = l2
l2 = l2.next
l1 = l1.next
l1.next = temp
else:
l1 = l1.next
return l