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
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home