Home

C# Create Linked List From Array

There are several ways but they seem rather uneccessarily complex. This starts from the right to left, building the list "backwards"

    static ListNode BuildListNodeBackwards(int[] iArray)
    {
        ListNode myHead = null;

        int i = iArray.Length;

        while(i-- > 0)
        {
            ListNode tempNode = new ListNode(iArray[i], null);
            if(myHead == null)
            {
                myHead = tempNode;
            }
            else
            {
                tempNode.next = myHead;
                myHead = tempNode;
            }
        }

        return myHead;
    }

Another way to do this is by making an array of ListNodes from the initial array...

    static ListNode BuildListNodeByArray(int[] iArray)
    {
        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];
    }

 

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