📅  最后修改于: 2023-12-03 15:23:38.175000             🧑  作者: Mango
在链表中交换第 K 个节点与从末尾开始的第 K 个节点,需要先遍历链表获取链表长度,然后再进行交换操作。
以下的代码均为示例代码,并非完整可运行的代码。
p
和 q
,分别指向第 K 个节点和第 $n-K+1$ 个节点。prev_p
、prev_q
、next_p
和 next_q
,用于保存交换节点的前继节点、后继节点,以及交换节点本身的前后节点。class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def swapNodes(head: ListNode, k: int) -> ListNode:
# 遍历链表,获取链表长度
n = 0
p = head
while p:
n += 1
p = p.next
# 判断链表是否有足够的节点进行交换
if k > n or k < 1:
return head
# 定义指针变量
p = head
q = head
for i in range(1, k):
p = p.next
for i in range(1, n - k + 1):
q = q.next
prev_p, prev_q, next_p, next_q = None, None, None, None
# 当交换节点不相邻时
if p != q.next and q != p.next:
prev_p = head
while prev_p.next != p:
prev_p = prev_p.next
prev_q = head
while prev_q.next != q:
prev_q = prev_q.next
next_p = p.next
next_q = q.next
# 交换节点
if prev_p:
prev_p.next = q
if q.next != p:
q.next = next_p
else:
q.next = p
if prev_q:
prev_q.next = p
if p.next != q:
p.next = next_q
else:
p.next = q
# 当交换节点相邻时
elif p == q.next:
prev_p = head
while prev_p.next != p:
prev_p = prev_p.next
next_q = q.next
# 交换节点
q.next = p
p.next = next_q
prev_p.next = q
elif p.next == q:
prev_q = head
while prev_q.next != q:
prev_q = prev_q.next
next_p = p.next
# 交换节点
p.next = q
q.next = next_p
prev_q.next = p
return head