I'm trying to create a method that will add a node to my linked list. The method takes an int (to specify where the new link should go) and String (because my linked list holds strings). I wrote some code that I thought would add a link at specific point in my list, however when I print my list after supposedly adding a new node, I see that the new node has not been added. I'm pretty surprised because I was careful about testing the behavior of my code as I was writing it, and the add method seems to do what I expect--but the newly printed list isn't reflecting the changes after adding a new link. Can anyone tell where I'm going wrong :/
ps: the names of the classes and methods are not up for debate, my teacher chose them and that's how they must stay.
thanks!
Test Linked List
class LinkedListTest
{
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.insertFirst("cat");
list.insertFirst("dog");
list.insertFirst("fish");
list.insertFirst("cow");
list.insertFirst("horse");
list.insertFirst("pig");
list.insertFirst("chicken");
list.add(3, "mouse");
list.print();
}
}
Linked List Class
public class LinkedList
{
private Link first;
public LinkedList()
{
first = null;
}
public void insertFirst(String word)
{
Link link = new Link(word);
link.next = first;
first = link;
System.out.print(first.item + " ");
}
public String deleteFirst()
{
Link temp = first;
first = first.next;
return temp.item;
}
public String get(int index)
{
Link current = first;
while (index > 0)
{
index--;
current = current.next;
}
return current.item;
}
public void add(int index , String someString)
{
Link current = first;
while (index>0)
{
index--;
current = current.next;
}
Link newLink = new Link(someString);
newLink.next = current;
current = newLink;
}
public void print()
{
System.out.println("-----------PRINTING LIST------------");
Link current = first;
while(!(current==null))
{
System.out.println(current.item);
current = current.next;
}
}
}
Link Class
public class Link
{
public String item;
public Link next;
public Link(String theItem)
{
item = theItem;
}
}