Original title address: http://oj.leetcode.com/problems/swap-nodes-in-pairs/
Given a linked list, swap every, adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. Modify the values in the list, only nodes itself can be changed.
Test Instructions: Swaps node 22 in the list. Given 1->2->3->4 , you should return the list as 2->1->4->3 .
problem-solving ideas: The problem is mainly related to the operation of the chain list. Add a head knot, it will be convenient to operate. Also with a [this picture is my Asrman original]
Code:
#Definition for singly-linked list.#class ListNode:#def __init__ (self, x):#self.val = x#Self.next = NoneclassSolution:#@param a ListNode #@return a ListNode defSwappairs (Self, head): Pre=listnode (0) Pre.next=Head Curr=Head Head=Pre whileCurr andCurr.next:#Curr =1, Curr.next =2Pre.next = Curr.next#0 --2Curr.next = Pre.next.next#1--3 # Curr.next.nextPre.next.next = Curr#3 --1Pre = Curr#pre = 1Curr = Curr.next#curr= 3 returnHead.next
Reference:
Https://oj.leetcode.com/discuss/3608/seeking-for-a-better-solution
[Leetcode]swap Nodes in Pairs @ Python