My accepted solution in Python, quite fast


  • 10
    B
    class Solution:
        # @param a ListNode
        # @return a ListNode
        def swapPairs(self, head):
            p1 = guard = ListNode(0)
            guard.next = head
            
            try:
                while True:
                    p0, p1, p2 = p1, p1.next, p1.next.next
                    p0.next, p1.next, p2.next = p2, p2.next, p1
            except:
                return guard.next

  • 0
    S

    Its very elegant !. Only caveat is the guard additional node added at the beginning. Otherwise great idea if you could sell this to the interviewer. Giving an upvote.


  • 0
    B

    Thanks for voting. For the using of a guard node, I think this is critical and the base of the unified approach of "return guard.next". Or we have to deal with the empty list (head == None), one node list and more-than-tow node list in different way. Any suggestion for that?


  • 4
    G

    An updated version based on yours that I personally think is more straightfoward

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param a ListNode
        # @return a ListNode
        def swapPairs(self, head):
            if not head:
                return None
            
            dummyNode = p0 = ListNode(0)
            dummyNode.next = head
            
            while p0.next and p0.next.next:
              p1, p2 = p0.next, p0.next.next
              p0.next, p1.next, p2.next = p2, p2.next, p1
              p0 = p0.next.next
             
            return dummyNode.next
    

  • 1
    R

    if not head: return this can be removed to make it even cleaner.

    class Solution:
    # @param {ListNode} head
    # @return {ListNode}
    def swapPairs(self, head):
        dummy = cur = ListNode(-1)
        dummy.next = head
        
        while cur.next and cur.next.next:
            p1, p2 = cur.next, cur.next.next
            cur.next, p1.next, p2.next = p2, p2.next, p1
            cur = cur.next.next
        return dummy.next
    

  • 0
    Q

    quite elegant, like this solution.


Log in to reply
 

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