Python solution. O(n)


  • 0
    H
    class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p = head
        if p == None:
            return None
        q = head.next
        if q == None:
            return head
        new_head = ListNode(0)
        new_head.val = q.val
        new_head.next = p
        while(q.next != None):
            temp = q
            if q.next.next == None:
                p.next = q.next
                break
            else:
                temp.val = q.next.next.val
                p = temp.next
                q = q.next.next
        if q.next == None:
            p.next = None
        return new_head

  • 0
    F

    "You may not modify the values in the list, only nodes itself can be changed."


Log in to reply
 

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