I’m trying to make a custom linked list, so far I’ve figured out how to make the general structure and the two easiest methods (insertFirst and deleteFirst). The next thing I want to do is make a get method that takes the index of a link and then returns the string at that location. I don’t have any index or address assigned to each link, so I don’t see how to refer to a specific location in my linked list. I see that if I write first.next I get the second item, and first.next.next I get the third item.. But I need to figure out how to make my index parameter (the one passed into the get method) correlate with the proper location in my list. How can I do this?
Here’s my code:
Test code:
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");
System.out.println(list.get(1));
}
}
My 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;
}
public String deleteFirst()
{
Link temp = first;
first = first.next;
return temp.toString();
}
public String get(int index)
{
// the following is just to show that I can access different links
// by adding more .next's after first--- but i need a way to access
// the correct link based on the index passed in
// String second = first.next.item;
String third = first.next.next.item;
// String fourth= first.next.next.next.item
return third;
}
}
public class Link
{
public String item;
public Link next;
//Link constructor
public Link(String theItem)
{
item = theItem;
}
}
Assuming that
get(0)returns you the first element:If you want to put this method inside
public class LinkedList:Alternatively, you can also implement this inside
public class Link:, but this is not advisable since it wastes space on your call stack:and inside public class LinkedList:
Hope this helps!