Search code examples
javalistlinked-list

How to set next value in a Circularly Linked List in Java?


This is what I have so far:

public void insert(int position, ValueNode value) {
  if (position == 1) {
    this.nextInRow = value;
  }
  ValueNode current = this.getFirst();
  if (position > 1) {
    current.setNext(current.next);
  }
    value.setNextInRow(current.getNext());
}

The headnode is being set properly with the first if statement. In this list we already know the position, so I'm thinking we don't need a while loop since we know where to put the new node.

I create a temp node called current to hold the next node pointer, but right now it sets the pointer to null. My problem is I don't know where to point the next node pointer to. Any help would be very much appreciated.


Solution

  • Distinguish making a node with value and setting next node operations.

    Your data structure can be like this:

    class Node {
       int val;
       Node next;
       Node previous;
    
      //setters and getters and constructors
    
    }
    

    1) For all new values should have a node

    Node createNode(int val) {
        Node newNode = new Node(val);
        newNode.next = null;
        newNode.previous = null;
        return newNode; 
    }  
    

    2) Locate newNode starting from root or hold a current node set it next

     currentNode.setNext(Node newNode);
     //iterate the currenNode with newNode
     currentNode = newNode;
    
     ...
    
     // implement the setNext and mark current as previous for newNode
     void setNextNode(Node newNode) {
          this.next = newNode;
          newNode.setPrevious(this); 
     }