I have successflully created a LinkedList from scratch. So far it can only add data. No deletion or anything fancy like that.
I can add strings, integers etc but I have a problem with printing the data I have added. How do I do that? I guess I'll have to loop through it first, but how?'
Here is my Node class:
public class Node {
T data;
Node<T> nextNode;
public Node(T data) {
this.data = data;
}
public String toString () {
return data +"";
}
}
Here is the LinkedList class:
public class LinkedList <T> {
Node<T> head;
Node<T> tail;
public void add (T data) {
// where to add statements. if its empty or not
Node<T> node = new Node<T> (data);
if (tail == null) { // empty list
// nothng in the node = tail = node;
head = node;
tail = node;
}
else { // non empty list, add the new boogie train to the tail
tail.nextNode = node; // new node pointing to tail
tail = node; // update
}
}
And here is the main. Where I create an object out of Linkedlist and use the generic add method to add my data. But how do i print it out on the screen? Thanks in advance.
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<Object> ();
list.add(15); // boogie1 = head
list.add(16);
list.add(10); // boogie end = tail