My python solution


  • 1
    B
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def swapPairs(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head or not head.next:
                return head
                
            odd = head #1
            even= head.next #2
            odd.next = even.next #1->3
            even.next = odd #2->1
            head = even #2
            while(odd.next and odd.next.next):
                temp = odd
                odd=odd.next
                even = odd.next
                odd.next = even.next
                even.next = odd
                temp.next = even
                
            return head
    

    use two pointers and swap them two at a time
    temp ->odd -> even ->x becomes
    temp->even->odd ->x


Log in to reply
 

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