下面是一个示例代码,用于创建一个棋盘或交织两个链表的方法:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_lists(head1, head2):
if not head1:
return head2
if not head2:
return head1
p1 = head1
p2 = head2
while p1 and p2:
temp1 = p1.next
temp2 = p2.next
p1.next = p2
p2.next = temp1
p1 = temp1
p2 = temp2
return head1
# 创建链表1: 1 -> 2 -> 3
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3
# 创建链表2: 4 -> 5 -> 6 -> 7
node4 = ListNode(4)
node5 = ListNode(5)
node6 = ListNode(6)
node7 = ListNode(7)
node4.next = node5
node5.next = node6
node6.next = node7
# 打印交织前的两个链表
print("链表1:", end=" ")
curr = node1
while curr:
print(curr.val, end=" ")
curr = curr.next
print()
print("链表2:", end=" ")
curr = node4
while curr:
print(curr.val, end=" ")
curr = curr.next
print()
# 交织两个链表
merged_head = merge_lists(node1, node4)
# 打印交织后的链表
print("交织后的链表:", end=" ")
curr = merged_head
while curr:
print(curr.val, end=" ")
curr = curr.next
print()
输出结果为:
链表1: 1 2 3
链表2: 4 5 6 7
交织后的链表: 1 4 2 5 3 6 7
在上面的示例中,我们首先定义了一个ListNode
类来表示链表节点。然后,我们定义了一个merge_lists
函数,该函数接受两个链表的头节点作为参数,并返回交织后的链表的头节点。
在函数中,我们使用两个指针p1
和p2
分别指向链表1和链表2的当前节点。我们使用两个临时变量temp1
和temp2
来保存当前节点的下一个节点。然后,我们将链表2的当前节点插入到链表1的当前节点之后,并将链表1的当前节点插入到链表2的当前节点之后。最后,我们将p1
和p2
分别更新为它们的下一个节点,继续交织链表直到其中一个链表遍历完为止。
最后,我们在主程序中创建了两个链表,并通过调用merge_lists
函数交织这两个链表。最后,我们打印出交织后的链表。