Home > other >  Logic Error: Inserting Last Node in a Linked List
Logic Error: Inserting Last Node in a Linked List

Time:01-08

I am coding a recursive Java method that adds an object node to the end of a linked list. However, instead of executing properly, my current implementation removes all other nodes and just stores the new object value. There are no compilation, runtime exception, or additional logic errors. How can I fix this? (If there is another Stack Overflow that answers this, please post the link.)

Method:

public static ListNode insertLast(ListNode head, Object arg) {
      return (head.getNext() != null) ? insertLast(head.getNext(), arg) : new ListNode(arg, null);
}

Where head = [computer, science, java, coffee, nonsense, boo, foo, hello], and arg = [p].

Expected (with an object value argument of 'p'): [computer, science, java, coffee, nonsense, boo, foo, hello, p]

Actual (with an object value argument of 'p'): [p]

ListNode Class Implementation (for reference):

public class ListNode {
  private Object value;
  private ListNode next;
  public ListNode(Object v, ListNode n) {
    value = v;
    next = n;
  }
  public Object getValue() {
    return value;
  }
  public ListNode getNext() {
    return next;
  }
  public void setValue(Object newv) {
    value = newv;
  }
  public void setNext(ListNode newn) {
    next = newn;
  }
}

CodePudding user response:

In your provided implementation, you are creating a new ListNode object for the new node to insert, but you are not attaching it to the linked list.

Assuming that you want the insertLast method to return the ListNode object for the node that was just inserted, you can use the following code:

public static ListNode insertLast(ListNode head, Object arg) {
    if (head.getNext() != null) {
        return insertLast(head.getNext(), arg);
    } else {
        ListNode newNode = new ListNode(arg, null)
        head.setNext(newNode);
        return newNode;
    }
}

The return value of the insertLast is the newly inserted node, not the head of the linked list. If you want the head of hte linked list, you should use the object that you passed in as the head parameter into insertLast.

  • Related