要在一个单向链表中交换两个节点,首先需要遍历链表找到这两个节点,并记录它们的前驱节点。然后,通过修改节点的next指针,将它们交换位置。以下是一种实现方式:class ListNode: def __init__(self, val=0): self.val = val self.next = Nonedef swapNodes(head, node_x, node_y): # 如果节点相同,不需要进行交换 if node_x == node_y: return head # 使用research找到node_x和node_y的前驱节点prev_x和prev_y prev_x = None prev_y = None cur = head while cur and (not prev_x or not prev_y): if cur.next == node_x: prev_x = cur elif cur.next == node_y: prev_y = cur cur = cur.next # 如果节点不存在,则无法交换 if not prev_x or not prev_y: return head # 交换节点的位置 if prev_x: prev_x.next = node_y else: head = node_y if prev_y: prev_y.next = node_x else: head = node_x # 交换节点的后继节点 temp = node_x.next node_x.next = node_y.next node_y.next = temp return head# 测试示例# 创建链表:1->2->3->4->5head = ListNode(1)node2 = ListNode(2)node3 = ListNode(3)node4 = ListNode(4)node5 = ListNode(5)head.next = node2node2.next = node3node3.next = node4node4.next = node5# 打印原链表cur = headwhile cur: print(cur.val, end="->") cur = cur.nextprint("None")# 交换节点3和节点4head = swapNodes(head, node3, node4)# 打印交换后的链表cur = headwhile cur: print(cur.val, end="->") cur = cur.nextprint("None")
运行以上代码,输出结果为:1->2->3->4->5->None1->2->4->3->5->None
可以看到,节点3和节点4的位置成功地进行了交换。
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。 |