24. 两两交换链表中的节点
此题需要注意交换的顺序。我们同样设置头指针__head
指向头结点head
。while cur and cur.next
表示具备两两交换的条件。
pre
指向temp
;cur
指向temp.next
;temp.next
指向cur
。
很明显,temp.next
是都涉及到的,所以23的顺序不能换,而第一步可以随意。
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = __head = ListNode(0, head)
cur = head
while cur and cur.next:
temp = cur.next
pre.next = temp
cur.next = temp.next
temp.next = cur
pre = cur
cur = cur.next
return __head. Next