The main purpose of this article is to complete the merging of 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.
"""
import numpy as np
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
"""单链表"""
class SingleLinkList(object):
def __init__(self):
self.__head = None
"""判断链表是否为空"""
def is_empty(self):
return self.__head == None
"""链表长度"""
def length(self):
# cur初始时指向头节点
cur = self.__head
count = 0
# 尾节点指向None,当未到达尾部时
while cur != None:
count += 1
# 将cur后移一个节点
cur = cur.next
return count
"""遍历链表"""
def travel(self):
cur = self.__head
while cur != None:
print(cur.val, end=" ")
cur = cur.next
print("")
"""尾部添加元素"""
def append(self, val):
node = ListNode(val)
# 先判断链表是否为空,若是空链表,则将_head指向新节点
if self.is_empty():
self.__head = node
# 若不为空,则找到尾部,将尾节点的next指向新节点
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
class Solution(object):
def mergeTwoLists(L1,L2):
"""
:type L1: ListNode
:type L2: ListNode
:rtype: ListNode
"""
head = cur = ListNode(0)
while L1 and L2:
if L1.val > L2.val:
cur.next = L2
L2 = L2.next
else:
cur.next = L1
L1 = L1.next
cur = cur.next
"""or 返回第一个为真的值"""
cur.next = L1 or L2
return head.next
if __name__=="__main__":
array1 = sorted(np.random.random_integers(1,15,5))
array2 = sorted(np.random.random_integers(1,10,5))
print('array1'+str(array1))
print('array2'+str(array2))
L1= SingleLinkList()
L2= SingleLinkList()
for each in array1:
L1.append(each)
for each in array2:
L2.append(each)
sol = Solution
# print(L1._SingleLinkList__head.val)
# print(L2._SingleLinkList__head.val)
L = sol.mergeTwoLists(L1._SingleLinkList__head, L2._SingleLinkList__head)
L3 = SingleLinkList()
L3._SingleLinkList__head = L
L3.travel()
The result of the operation is
![](https://i-blog.csdnimg.cn/blog_migrate/5d31d66eeeac03b3b945e51d86d276e8.png)