My Simple C# Solution


  • 0
    H
    public ListNode SwapPairs(ListNode head) 
    {
            ListNode returnHead = new ListNode(0);
            ListNode FirstNode;
            ListNode ThirdNode;
            ListNode PreviousNode = null;
    
            if (head == null || head.next == null)
                return head;
    
            returnHead = head.next;
    
            while (head.next != null)
            {
                FirstNode = head;
                ThirdNode = head.next.next;
                head = head.next;
                head.next = FirstNode;
                head.next.next = ThirdNode;
                if (PreviousNode != null)
                {
                    PreviousNode.next = head;
                    PreviousNode = head.next;
                }
                else
                    PreviousNode = head.next;
    
                if (ThirdNode == null)
                    break;
                else
                    head = ThirdNode;
            }
    
            return returnHead;
    }

Log in to reply
 

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