给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
step1: 借助一个头节点,方便后续修改指针指向操作
step2: 借助三个指针:pre, cur, last
cur: 指向 一组k个节点 的第一个节点
last: 指向 一组k个节点 的最后一个节点
pre: 指向 待交换一组k个节点 的前一个节点
例如,当 k=3 时,先找到 pre, cur, last 所指向的节点:
step3: 翻转k个一组链表
step4: 重复step2, step3,直到遍历所有节点
from typing import *class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextclass Solution:def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:if k==1: return head## step1:pre = ListNode(val=-1, next=head)head = prewhile pre.next:## step2: cur = last = pre.nextcount = 1while count1:temp = curcur = cur.nextcount -= 1temp.next = last.nextlast.next = tempif k-count==1: pre = temp## if cur==last: pre = tempreturn head.next