In Java, I have been asked to store integer values in a singly-linked list and then print the elements stored in the list. Here is what I came up with:
int max = 10;
List<Integer> list = new ArrayList<Integer>();
for (int num = 0; i < max; i++){
list.add(num);
}
System.out.print(list);
I was wondering, is ArrayList the same thing as a singly-linked list? I want to make sure that I’m answering the question correctly. Does this make sense? Thanks!
No –
ArrayListis not a linked list at all – it’s an array list.ArrayListstores its elements in an array, whereas linked lists store them in arbitrary memory by linking objects together.LinkedListis a doubly-linked list, and I’m sure that there are various singly linked list implementations you could grab, but given that this is an assignment you’ll either be marked down or fail outright if you try to hand in code using someone else’s implementation.Instead, find an article etc. which describes linked lists and try to implement one yourself.
Generally these are built in java by having a class
SomeClasscontaining a forward link of typeSomeClassand a value. You build the list by linking eachSomeClassinstance to the next through the forward link.