LeetCode Medium:24. Swap Nodes in Pairs

1. The topic

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.

It means that given a linked list, reverse two adjacent nodes.

2. Ideas

define a head

3. Code

#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

The result you will get is 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)

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324644040&siteId=291194637