Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Linked List - add method
    text
    copied!<p>Data structures class, implementing a singly linked-list with head, tail and current nodes. Having trouble with a method, could use a nudge in the right direction.</p> <p>From the assignment, write the method:</p> <p>add( item ) : adds the item (String) after the current node in the list and sets the current pointer to refer to the new node.</p> <p>My attempt:</p> <pre><code>public void add(String item) { if(curr != null) { Node newNode = new Node(item, curr.next); curr.next = newNode; curr = newNode; } else { head = tail = new Node(item, null); curr = head; } } </code></pre> <p>My add method only seems to work when I'm adding items to the middle of the list, not on either end. If I use it to add a few items and then print the list, only the first one I added will be on the list, while my prepend and append methods have tested just fine.</p> <p>Is there any glaring issue with my code? I feel like I'm missing something obvious.</p> <p>All:</p> <pre><code>public class LinkedList { Node head = null; /* Head of the list */ Node tail = null; /* Tail of the list */ Node curr = null; /* Current node in the list */ public void prepend(String item) { if (head == null) { head = tail = new Node(item, null); curr = head; } else { head = new Node(item, head); curr = head; } } public void append(String item) { if (head == null) { head = tail = new Node(item, null); curr = tail; } else { tail.next = new Node(item, null); tail = tail.next; curr = tail; } } public void add(String item) { if (curr != null) { Node newNode = new Node(item, curr.next); curr.next = newNode; curr = newNode; } else { head = tail = new Node(item, null); curr = head; } } public void delete() { if (curr.next == null) { Node temp = head; while (temp.next != curr) { System.out.println(temp.item); temp = temp.next; } temp.next = null; curr = head; } } public void find(String item) { Node temp = new Node(curr.item, curr.next); if (item.equals(temp.item)) curr = temp; else { temp = temp.next; while (temp.next != null &amp;&amp; temp != curr) { if (item.equals(temp.item)) curr = temp; } } } public String get() { if (curr != null) return curr.item; else return ""; } public boolean next() { if (curr != tail) { curr = curr.next; return true; } else return false; } public void start() { curr = head; } public void end() { curr = tail; } public boolean empty() { if (head == null) return true; else return false; } } </code></pre> <p><code>Node</code> class:</p> <pre><code>class Node { Node next; String item; Node(String item, Node next) { this.next = next; this.item = item; } } </code></pre>
 

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