#New Inserting Problem

3 messages · Page 1 of 1 (latest)

elder shoal
#

Okay. Yay! Teacher told us how to insert yay! now.. the list wont print the next values.. do I need a new node thingy ```public void insert(int value, int position) {
Node newNode = new Node(value);

    if (position < 0 || position > size()) { // checks if the position is a negative number or bigger than size
        throw new IndexOutOfBoundsException("Position must be in the range [0, size]");
    }
    if (head == null) { // the list is empty if the list is null
        head = newNode; // the new node becomes the first node
    } else {
        Node current = head;
        int count = 0;
        while (current.getNext() != null) { // while the node is not empty
            current = current.getNext(); // it runs through the values
            count++;
            if (count == position - 1) {   // find the one right before it
                current.setNext(newNode); // insert the value
            }
            current = current.getNext(); // add the test of the values to the list
        }
    }
}
old sailBOT
#

This post has been reserved for your question.

Hey @elder shoal! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.