链表成对反转

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

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
     """
     思路:
      1、需要定义一个变量存储新的head节点
      2、判断循环的判断条件:后面两个节点同时存在
      3、每次循环需要操作的元素
        pre:当前第一个节点的前驱节点
        a:当前第一个节点
        b:当前第二个节点(a的后继节点)
        b.next:当前第二个节点的 后继
        所以,每次循环共计涉及 4个节点,3个指针 : 由 pre -> a -> b -> (c = b.next) 变换为 pre -> b -> a -> c
        
      4、每次循环的最后,需要更新变量 pre 的指向(也就是pre = a),为下一次循环准备工作。
               
     """
        pre = self
        # 定义了next变量,用于存放head节点
        self.next = head
        while pre.next and pre.next.next:
            a = pre.next
            b = pre.next.next
            # pre->a->b->c  变换为 pre->b->a->c
            pre.next ,b.next,a.next = b,a,b.next

            pre = a
        
        # 返回head,新的head节点存储在self对象的next变量中
        return self.next
原文地址:https://www.cnblogs.com/wl413911/p/12921345.html