My Python Code ( Not Recursion Approach )


  • 1
    R
    # 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:
                return head
                
            pt1 = head
            
            if not pt1.next:
                return head
            else:
                pt2 = head.next
                
            while True:
                pt1.val, pt2.val = pt2.val, pt1.val
                if not pt2.next:
                    break
                else:
                    pt1 = pt2.next
                
                if not pt1.next:
                    break
                else:
                    pt2 = pt1.next
            
            return head
    
    

  • 0
    J

    @Rebirth I have simplied your code and it passed all tests.

    class Solution(object):
        def swapPairs(self, head):
            if not head or not head.next: return head 
            p1=head
            while p1 and p1.next:
                p1.val,p1.next.val=p1.next.val,p1.val
                p1=p1.next.next
                if not p1 or not p1.next:
                    return head
            return head
    

Log in to reply
 

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