LeetCode Medium:24. Swap Nodes in Pairs

一、题目

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

Example:

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

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.

意思就是给定一个链表,反转相邻的两个结点。

二、思路

定义一个head

三、代码

#coding:utf-8
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p = ListNode(0)
        p.next = head
        head = p
        while p.next != None and p.next.next != None:
            s = p.next.next
            p.next.next = s.next
            s.next = p.next
            p.next = s
            p = s.next
        print("after:",head.next.val,head.next.next.val,head.next.next.next.val,head.next.next.next.next.val)
        return head.next

"""
idx = ListNode(3)
n = idx
n.next = ListNode(4)
n = n.next
n.next = ListNode(5)
n = n.next
return idx

你将得到的结果是 3 -> 4 -> 5
"""
if __name__ == '__main__':
    idx = ListNode(3)
    n = idx
    n.next = ListNode(4)
    n = n.next
    n.next = ListNode(5)
    n = n.next
    n.next = ListNode(6)
    n = n.next
    print("before:",idx.val,idx.next.val,idx.next.next.val,idx.next.next.next.val)
    ss = Solution()
    ss.swapPairs(idx)

  

猜你喜欢

转载自www.cnblogs.com/xiaodongsuibi/p/8906577.html