Share my C# solution


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
    * }
    */
    
    //unit test [1], [1,2],  [1, 2, 3], [1,2,3,4]
    public class Solution {
    public ListNode SwapPairs(ListNode head) {
        
        //check null
        if(head==null||head.next==null)
            return head;
        //need to build a fack new header
        var newHeader=new ListNode(0);
        newHeader.next=head;
        var pre=newHeader;
        var cur=head;
        var nex=head.next;
        
        while(nex!=null)
        {
            cur.next=nex.next;
            nex.next=cur;
            pre.next=nex;
            if(cur.next==null)  //when to stop
                break;
            pre=cur;
            nex=cur.next.next;
            cur=cur.next;
        }
        
        return newHeader.next;
        
        }
    }

Log in to reply
 

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