方法一:
- 主要思想:先取出两个链表的元素,合并到一个列表中,然后再进行排序,之后再创建一个链表
- 但这种方法不是最优==
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self,l1: ListNode, l2: ListNode) -> ListNode:
# if self.isEmpty():
# exit(0)
if l1 == None:
return l2
if l2 == None:
return l1
print('\rlink list traving result: ')
p = l1
p1 = l2
l_1 = []
l_2 = []
while p:
print(p.val)
l_1.append(p.val)
p = p.next
while p1:
print(p1.val)
l_1.append(p1.val)
p1 = p1.next
print(l_1)
l_1 = sorted(l_1)
print(l_1)#先取出两个链表,然后合并成一个,再创建链表,但是这种方法并不是最优
# print(self.initList(l_1))
index = len(l_1)
# def initList(self, val):
#创建头结点
head = ListNode(l_1[0])
p = head
#逐个为 val 内的数据创建结点, 建立链表
for i in l_1[1:]:
node = ListNode(i)
p.next = node
p = p.next
return head
方法二:
迭代法
- 首先设置一个哨兵位置,为了方便以后返回整个合并好的链表
- 依次比较两个链表中每个位置数值的大小,较小的先进行插入新的合并链表。
- 如果两个链表中一个链表已经插入完,则把另外一个链表顺序插入即可。
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# if self.isEmpty():
# exit(0)
if l1 == None:
return l2
if l2 == None:
return l1
prehead = ListNode(0)#设置一个哨兵
pre = prehead
# prehead.next = pre
# pre = prehead.next#更改节点的位置
p1 = l1
p2 = l2
# while p1:
# print(p1.val)
# p1 = p1.next
# while p2:
# print(p2.val)
# p2 = p2.next
while p1 != None and p2 != None:
if p1.val <= p2.val:
node = p1#更改节点的值需要两步
pre.next = node
pre = pre.next
# pre = pre.next#之后指针后移
p1 = p1.next
else:
node = p2
pre.next = node
pre = pre.next
# pre = prehead.next
p2 = p2.next
if p2 != None:
node = p2
pre.next = node
pre = pre.next
p2 = p2.next
elif p1 != None:
node = p1
pre.next = node
pre = pre.next
p1 = p1.next
else:
return prehead.next
return prehead.next