Home > Enterprise >  How can I convert a Linked List into an Array?
How can I convert a Linked List into an Array?

Time:10-18

I am working on a project for my Data Structures class that asks me to write a class to implement a linked list of ints.

  • Use an inner class for the Node.
  • Include the methods below.
  • Write a tester to enable you to test all of the methods with whatever data you want in any order.

I have to create a method called "public int[] toArray()". This method is meant to "Return an array of ints that contain all of the ints in the list." I have my code for this method down below. However, when I try to convert an array to a list my code does not work. When I run the code I get an array filled with the head value. For example, if I have a list [9, 15, 3, 16, 5, 1, 17, 6, 2, 9]. My output is [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]. I've tried looking it up but the code doesn't match up with the way my project is set up. Does someone know how to convert a Linked List into an Array?

import java.util.Random;
import java.util.Scanner;

public class LinkedListOfInts {
    Node head;
    Node tail;

    private class Node {
        int value;
        Node nextNode;

        public Node(int value, Node nextNode) {
            this.value = value;
            this.nextNode = nextNode;
        }

    }

    public LinkedListOfInts(LinkedListOfInts other) {
        Node tail = null;
        for (Node n = other.head; n != null; n = n.nextNode) {
            if (tail == null)
                this.head = tail = new Node(n.value, null);
            else {
                tail.nextNode = new Node(n.value, null);
                tail = tail.nextNode;
            }
        }
    }

    public LinkedListOfInts(int[] other) {
        Node[] nodes = new Node[other.length];
        for (int index = 0; index < other.length; index  ) {
            nodes[index] = new Node(other[index], null);
            if (index > 0) {
                nodes[index - 1].nextNode = nodes[index];
            }
        }

        head = nodes[0];
    }

    public LinkedListOfInts(int N, int low, int high) {
        Random random = new Random();
        for (int i = 0; i < N; i  )
            this.addToFront(random.nextInt(high - low)   low);
    }

    public void addToFront(int x) {
        head = new Node(x, head);
    }

    public int[] toArray() {
        int i = 0;
        int[] array = new int[getLength()];
        for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
            array[i  ] = head.value;
        }
        return array;

    }

    public String toString() {
        String result = " ";
        for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
            result  = ptr.value   " ";
        return result;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
        LinkedListOfInts copy = new LinkedListOfInts(list);
        boolean done = false;
        while (!done) {
            System.out.println("1. Reverse");
            System.out.println("2. toString");
            switch (input.nextInt()) {
            case 11:
                System.out.println("Array");
                System.out.println(list.toArray());
                break;
            case 12:
                System.out.println("toString");
                System.out.println(list.toString());
                break;
            }
        }
    }
}

CodePudding user response:

The idea is to crawl through the linked list from the head to the tail, and then store all elements. You are in fact already doing that with the toString() method.

As you do not know the amount of elements in the linked list, you will need to dynamically increase the size of the array. Within java, I would personally just recommend to use a list.

So the method would be along the lines of:

public Integer[] toArray() {
    ArrayList<Integer> list = new ArrayList();
    for(Node node = head; head != null; head = head.nextNode) {
        list.add(node.value);
    }
    return (Integer[]) list.toArray();
}

Note that I am currently directly accessing the node.value, which is somewhat fine given that it is in fact part of the codebase of the class. However, a better alternative is to use getters (and make every internal value private). I am however not sure they have thought you the concept of encapsulation yet, but it is very important within Java.

CodePudding user response:

public int[] toArray() {
    int i = 0;
    int[] array = new int[getLength()];
    for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
        array[i  ] = ptr.value;
    }
    return array;
}
  • Related