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
这个实现过程本来很简单,但是由于python用的不熟练,对链表操作不熟练,导致用了很久。
# 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 not l1 and not l2:
return None
l3=ListNode(0)
l4=l3
while l1 and l2:
if l1.val<=l2.val:
l3.next=l1
l1=l1.next
else :
l3.next=l2
l2=l2.next
l3=l3.next
l3.next=l1 or l2
return l4.next
注意:
1、python中没有Null,用None代替
2、我开始实现过程用的是l3=ListNode(),提示没有参数,后来我用了l3=ListNode(None),但是操作过程中还是有问题,最后看了别人的代码才知道,一般设置一个头结点,l3=ListNode(0),使用的时候直接使用l3.next。
3、我在写的过程中定义了l3=ListNode(0),然后l3=l3.next,再使用l3.val的时候提示没有val值,是因为l3虽然指向了下一个节点,但是下一个节点确实是空的,这和定义l3=ListNode()后再使用第一个节点有点像,所以这个代码是使用了l3.next=l1或者l3.next=l2。虽然这个时候l3后面有很多不是咱们想要的节点,但是咱们接下来每步都会操作l3.next,所以不会影响最终的结果
4,注意python的if not l1 and not l2用法(只要l1不为空,就是真),包括while l1 and l2 也是这种用法。以后后面的l3.next=l1 or l2