【LeetCode每天一题】Swap Nodes in Pairs

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.

将相邻的两个节点进行交换,在不交换值的前提条件下,只对节点指针进行交换。   时间复杂度为o(n),空间复杂度为O(1)。

思路: 可以利用链表中的哨兵机制来简化操作。具体操作步骤如下:

   

    

 1 class Solution(object):
 2     def swapPairs(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: ListNode
 6         """
 7         GuardNode = p = ListNode(0)
 8         GuardNode.next = head
 9         
10         while head and head.next:
11             tem = head.next         # 指向第二个节点
12             head.next = tem.next # 第一个节点指向第三个节点
13             tem.next = head        # 第二个节点指向第一个节点
14             p.next = tem             # 哨兵指向反转后的第一个节点
15             p = head                   # 指向下两个待反转节点的前一个节点。
16             head = head.next     # 指向下面即将反转的第一个节点
17         
18         return GuardNode.next
原文地址:https://www.cnblogs.com/GoodRnne/p/10580333.html