Note that there are some explanatory texts on larger screens.

plurals
  1. POMaking a custom linked list class -- need help implementing get method
    primarykey
    data
    text
    <p>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? </p> <p>please excuse any sloppy code...I'll be sure to clean up the details after I get a grasp on the linked list structure. </p> <p>Here's my code, thanks in advanced!</p> <p><strong>Test code</strong></p> <pre><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)); } } </code></pre> <p><strong>My class</strong> </p> <pre><code>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; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload