Python solution


  • 0
    W

    Simple and straightforward solution

    class Solution(object):
        def swapPairs(self, head):
    		"""
    		:type head: ListNode
    		:rtype: ListNode
    		"""
    		if not head:
    			return head
    
    		if head.next == None:
    			return head
    
    		temp0 = head
    		temp1 = head.next
    
    		temp0.next = temp1.next
    		temp1.next = temp0
    
    		temp0 = temp1
    		head = temp0
    		temp1 = temp0.next
    
    		while temp1.next != None:
    
    			if temp1.next.next != None:
    
    				temp0 = temp0.next
    				temp1 = temp1.next
    				temp2 = temp1.next
    
    				temp1.next = temp2.next
    				temp2.next = temp1
    				temp0.next = temp2
    
    				temp1 = temp2
    				temp2 = temp1.next
    
    				temp0 = temp0.next
    				temp1 = temp1.next
    
    			else:
    				break
    
    		return head

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.