My C# solution with dummy node


  • 0
    S
    public ListNode SwapPairs(ListNode head) {
            if(head==null || head.next==null)
                return head;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode pre = dummy;
            while(pre.next!=null && pre.next.next!=null)
            {
                var first = pre.next;
                var second = pre.next.next;
                first.next = second.next;
                pre.next = second;
                second.next = first;
                pre = first;
            }
            return dummy.next;
        }
    

Log in to reply
 

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