What you have coded is not a LinkedList, at least not one that I recognize. For this assignment, you want to create two classes:
LinkNode
LinkedList
A LinkNode
has one member field for the data it contains, and a LinkNode
reference to the next LinkNode
in the LinkedList
. Yes, it's a self referential data structure. A LinkedList
just has a special LinkNode
reference that refers to the first item in the list.
When you add an item in the LinkedList
, you traverse all the LinkNode's
until you reach the last one. This LinkNode's
next should be null. You then construct a new LinkNode
here, set it's value, and add it to the LinkedList
.
public class LinkNode {
String data;
LinkNode next;
public LinkNode(String item) {
data = item;
}
}
public class LinkedList {
LinkNode head;
public LinkedList(String item) {
head = new LinkNode(item);
}
public void add(String item) {
//pseudo code: while next isn't null, walk the list
//once you reach the end, create a new LinkNode and add the item to it. Then
//set the last LinkNode's next to this new LinkNode
}
}