title :
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.
code : OJ Test via runtime:42 ms
1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8 #@param a ListNode9 #@return a ListNodeTen defSwappairs (Self, head): One ifHead isNoneorHead.next isNone: A returnHead - -Dummyhead =listnode (0) theDummyhead.next =Head - -Pre =Dummyhead -Curr =Head + whileCurr is notNone andCurr.next is notNone: -TMP =Curr.next +Curr.next =Tmp.next ATmp.next =Pre.next atPre.next =tmp -Pre =Curr -Curr =Curr.next - returnDummyhead.next
Ideas :
Basic linked list operations.
It is important to note that while loop judgment condition: First Judge Curr not empty, then judge Curr.next not empty.
This and judgment condition has a short circuit function, and if the Curr is empty it will not make the next judgment, so it is safe
Leetcode "Swap Nodes in Pairs" Python implementation