给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
step1: 借助一个头指针,方便后续修改指针指向操作
step2: 借助三个指针:pre, cur, last
cur: 指向两两交换的节点的第一个节点
last: 指向两两交换的节点的最后一个节点
pre: 指向待交换节点的前一个节点
step3: 修改cur, last, pre三个节点指针,实现两两节点交换操作,如下图所示:
step4: 重复step2, step3,直到遍历所有节点
from typing import *class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextclass Solution:def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:if head==None or head.next==None:return headpre = ListNode(val=-1,next=head)cur = headlast = head.nexthead = prewhile True:## pre, cur, lastcur.next = last.nextlast.next = curpre.next = last## pre, last, curif cur.next==None or cur.next.next==None: breakpre = curcur = pre.nextlast = pre.next.nextreturn head.next