题目:
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(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None :
return l2
if l2 == None :
return l1
head = ListNode(0)
cur = ListNode(0) #新链表的最后一个结点
if l1.val < l2.val : #确定头结点
head = l1
cur = head
l1 = l1.next
else :
head = l2
cur = head
l2 = l2.next
while l1 != None and l2 != None : #循环合并
if l1.val < l2.val :
cur.next = l1
cur = cur.next
l1 = l1.next
else :
cur.next = l2
cur = cur.next
l2 = l2.next
if l1 == None :
cur.next = l2
if l2 == None :
cur.next = l1
return head