24. 两两交换链表中的节点

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

解法一:

一次遍历,用i,j指针表示前后结点对,pre记录i前驱,将i和j交换。

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        Head = ListNode(0)
        Head.next = head
        if not head or not head.next:
            return head
        pre, i ,j = Head, head, head.next
        while i and j:
            #交换
            i.next = j.next
            j.next = i
            pre.next = j
            #更新
            pre = i
            i = i.next
            if i:    #若i非空才有j
                j = i.next
        return Head.next

最后更新于