0
votes

I need help writing this addAfterCurrent method for my PerformanceList Which is a doublely linked list with a standerd head , tail and cursor(current) nodes declared. The node class uses

PerformanceNode next; PerformanceNode previous;

as pointers they also have set and get methods public void addAfterCurrent(PerformanceNode newPerformance)

Method Definiton Inserts the new data into the PerformanceList such that the new node directly follows the current node, if it exists. If there is no current node (i.e., the current node is null), simply insert the node at the end of the list. The current node should now be the newly created node

My current method does not insert a node after the current node .This is the problem i need help with I cant get it to set a newPerformance after the current node

public void addAfterCurrent(PerformanceNode element)
    {
        PerformanceNode temp = element;
        if (cursor == null)
        {
        head = temp;
        tail = temp;
        cursor = temp;
        }
        else
        {
            temp.setNext(cursor);
            cursor.setPrev(temp);

            cursor = temp;

            if(cursor == null)
            {
                tail = cursor;
            }
        }

    }
1
Currently, it sets the prev pointer of the node after it. Shouldn't it also set the next pointer of the node before it? Otherwise you'll see the node when going backwards, but not when going forwards.user253751

1 Answers

0
votes

I implemented with some comments according to the definition:

public void addAfterCurrent(PerformanceNode node) {
    if (node == null)  {
        throw new IllegalArgumentException("Node to be added cannot be null!");
    }

    if (cursor == null && tail == null) {
        throw new IllegalStateException("There is neither current nor tail node!");
    }

    if (cursor == null) { // there is no current node
        // insert the node at the end of the list
        tail.setNext(node);
        node.setPrev(tail);

        // mode end cursor
        tail = node; 

        // current node should now be the newly created node
        cursor = node;
    } else { // there is current node
        PerformanceNode temp = cursor.getNext();

        // new node directly follows the current node 
        cursor.setNext(node);
        node.setPrev(cursor);

        if (temp != null) {
            node.setNext(temp);
            temp.setPrev(node);
        } else { // current node was the last node
            tail = node; // mode end cursor
        }
    }
}