How to convert a Singly Linked List to an Array in Java

In this tutorial, we would learn how to convert a singly linked list to an array in Java.

Before beginning with the tutorial you must be clear as to what is a singly linked list and initializing, traversing, and adding to the list in Java.

Initializing the Linked List

public class List {
    private Node head;
    private class Node {
        private int value;
        private Node Next;

        public Node(int value) {
            this.value = value;
            this.Next = null;
        }
    }

    public int listSize() {
       Node iteratorNode = head;
        int ret = 0;
        while (iteratorNode != null) {
            ret++;
            iteratorNode = iteratorNode.Next;
        }
        return ret;
    }

    public void insert(int value) {
        Node newNode = new Node(value);
        if (head == null) {
            head = newNode;
        } else {
            Node node = head;
            while (node.Next != null) {
                node = node.Next;
            }
            node.Next = newNode;
        }
    }

    public int[] listToArray() {
        int[] array = new int[listSize()];
        Node node = head;
        int i = 0;
        while (node != null) {
            array[i] = node.value;
            i++;
            node = node.Next;
        }
        return array;
    }
}

In this code block, we are declaring a singly linked list with only a single default function that is to insert a value to the linked list.

The functions listSize() is to return the value of no of nodes in the linked list. The function can be replaced by creating a member variable that is incremented with each insertion and decremented with each deletion.

This value is required to initialize an array of n size for the n nodes.

 

The function listToArray() is the most important and needed to be explained.

public int[] listToArray() {
    int[] array = new int[listSize()];
    Node node = head;
    int i = 0;
    while (node != null) {
        array[i] = node.value;
        i++;
        node = node.Next;
    }
    return array;
}

First, an array of size n is initialized, n being the list size.

Then an iterator ‘i’ is created to store the value of the ith node on the ith place of the array.

Main driver Function

public class Main {
    public static void main(String[] args) {
        List l = new List();
        for (int i = 0; i < 5; i++) {
            l.insert(i* 10);
        }
        int[] array = l.listToArray();

        for (int i = 0; i < array.length; i++) {
            System.out.print("| " + array[i] + " |");
        }
    }
}

For example, we are just adding the values {0,10,20,30,40} to the list and print out the array.

Output:

| 0 || 10 || 20 || 30 || 40 |

Leave a Reply

Your email address will not be published. Required fields are marked *