用 Python 编写程序来交错两个链表中的列表元素
pythonserver side programmingprogramming更新于 2026/1/17 5:00:17
假设我们有两个链表 l1 和 l2,我们必须通过从 l1 开始交错这两个列表的元素来返回一个链表。如果链接列表中有任何剩余节点,则应将它们附加到列表中。
因此,如果输入为 l1 = [5,4,6,3,4,7] l2 = [8,6,9],则输出将为 [5,8,4,6,6,9,3,4,7]
为了解决这个问题,我们将遵循以下步骤 −
ans := l1
当 l2 不为空时,执行
如果 ans 不为空,则
如果 ans 的下一个不为空,则
newnode := 具有与 l2 相同值的新列表节点
newnode 的下一个:= 下一个ans
下一个 ans := newnode
ans := 下一个新节点
ans := 下一个新节点
l2 := 下一个 l2
否则,
下一个ans := l2
退出循环
否则,
return l2
return l1
让我们看看下面的实现以便更好地理解 −
示例
Source Code (Python):
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def solve(self, l1, l2):
ans = l1
while l2:
if ans:
if ans.next != None:
newnode = ListNode(l2.val, None)
newnode.next = ans.next
ans.next = newnode
ans = newnode.next
l2 = l2.next
else:
ans.next = l2
break
else:
return l2
return l1
ob = Solution()
l1 = make_list([5,4,6,3,4,7])
l2 = make_list([8,6,9])
res = ob.solve(l1,l2)
print_list(res)
输入
[5,4,6,3,4,7],[8,6,9]
输出
[5, 8, 4, 6, 6, 9, 3, 4, 7, ]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

