Home

C# Swap Nodes in Pairs

Another LeetCode question. This scored slightly better than average in the speed but below average in the memory usage.

public class Solution
{
    //https://leetcode.com/problems/generate-parentheses/

    public static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("Enter the first listNode");
            string s = Console.ReadLine();
            ListNode list1 = BuildListNodeFromString(s);
            ListNode result = SwapPairs(list1);
        }

    }

    static public ListNode SwapPairs(ListNode head)
    {
        List<ListNode> listNodes = new List<ListNode>();
        while(head != null)
        {
            listNodes.Add(new ListNode(head.val, null));
            head = head.next;
        }

        for (int i = 0; i < listNodes.Count - 1; i += 2)
        {
            ListNode holder = listNodes[i];
            listNodes[i] = listNodes[i + 1];
            listNodes[i + 1] = holder;
        }

        if(listNodes.Count == 0)
        {
            return null;
        }

        for (int i = 0; i < listNodes.Count - 1; i++)
        {
            listNodes[i].next = listNodes[i + 1];
        }

        return listNodes[0];
    }

    static ListNode BuildListNodeFromString(string s)
    {
        s = s.Replace("[", "");
        s = s.Replace("]", "");
        string[] sArray = s.Split(",");
        int[] iArray = Array.ConvertAll(sArray, x => int.Parse(x));

        ListNode[] listNodeArray = new ListNode[iArray.Length];
        for (int i = 0; i < iArray.Length; i++)
        {
            listNodeArray[i] = new ListNode(iArray[i], null);
        }
        for (int i = 0; i < listNodeArray.Length - 1; i++)
        {
            listNodeArray[i].next = listNodeArray[i + 1];
        }

        return listNodeArray[0];
    }

    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int val = 0, ListNode next = null)
        {
            this.val = val;
            this.next = next;
        }
    }
}

 

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog