Iterative Python Code


  • 0
    B
    class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        if not head:
            return head
        
        vhead=ListNode(0)
        vhead.next=head
        lastnode=vhead
        
        one=lastnode.next
        two=one.next
        if not two:
            return vhead.next
        nextnode=two.next
        
        two.next=one
        one.next=nextnode
        lastnode.next=two
        
        while nextnode:
            lastnode=one
            one=nextnode
            two=one.next
            if not two:
                return vhead.next
            nextnode=two.next
            
            two.next=one
            one.next=nextnode
            lastnode.next=two
            
        return vhead.next
    

    basically keep loose strings tight. maintain a node called lastnode and next node. and two nodes in between


Log in to reply
 

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