C# - iterative - use of previous pointer for clarity


  • 0
    public ListNode SwapPairs(ListNode head) 
    {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode prev = dummyHead;
        ListNode curr = head;
        
        while (curr != null && curr.next != null)
        {
            ListNode next = curr.next;
            ListNode nextnext = next.next;
            prev.next = next;
            next.next = curr;
            curr.next = nextnext;
            
            prev = curr;
            curr = curr.next;
        }
        
        return dummyHead.next;
    }

  • 0
    C

    Good way to deal the first node!


Log in to reply
 

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