24. Swap Nodes in Pairs

【Description】

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

【Idea】

考察链表的基本操作

注意每对节点逆置时, 同时更新头结点的指向

【Solution】

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head is None:
            return head
        pre, pre.next = self, head     # 向前设置一个节点的目的是为了便于每次逆置后更新(temp)头结点的指向
        while pre.next and pre.next.next:
            a = pre.next
            b = a.next
            pre.next, b.next, a.next = b, a, b.next
            pre = a
        return self.next

你可能感兴趣的:(24. Swap Nodes in Pairs)