Home > database >  a method about array algorithm
a method about array algorithm

Time:11-19

class Node {
    public int value;
    public Node next;
}

    private static Node GenerateList(params int[] array) {
        Node node = null;
        for (int i = a.Length - 1; i >= 0; i--) { 
            node = new Node { value = array[i], next = node }; 
        }
        return node;
    }

This GenerateList method makes a list from an array, but I can not understand node = new Node { value = array[i], next = node };.

Fir example, in the first loop: node is equal to a new node, but new node's next node points to the older node. In the second loop, the second new node is equal to the first node, the second new node's node will point to the first node, but what will happen to second node?

What am I not understanding?

CodePudding user response:

Let me try to explain but not sure that is what you looking for.

It seems like it convert Array to LinkList and more specifically Queue.

Now if you look at the for loop carefully then it is in reverse order.

  1. At first iteration node = null. At that time it will get last element from array and create node and assign next to null. This process assign new reference to node variable.

  2. Now for second iteration , it will assign second last value from array to node value and at that time it will assign previously create node as next.

This will it will reach to first value and node.

From if you have just reference of node and if you start looking for next node is there or not then it will go upto last value of array.

CodePudding user response:

This is an array to the link list algorithm.
input: array
output: link list

The starting node is set with the last element of the array. The next is set with the nearest item in the array that will be set in the next iteration of the loop. in each step, you move backwards in the array till the start of the array.

  • Related