Search code examples
javalinked-listcircular-list

Circular linked list and access to previous/next from inside of node


I need circular list of objects. And each one should know which is previous or next. I did this:

class Bus {

    private Bus previous;
    private Bus next;

    public Bus() {
      //anything
    }

    public void setPrevious(Bus bus) {
      this.previous = bus;
    }

    public void setNext(Bus bus) {
      this.next = bus;
    }

    private void someMethod() {
     // if (previous.xxx() && next.xxx()) {
     //   do something
     // } 
    }

}

And I created an array of Bus. After I add all buses into it, I set next and previous of each element. And I feel it's ugly:D. May you suggest me better way?


Solution

  • If you adjust your setNext and setPrevious methods to not only update their instance but also the instance that is set as next and as previous you want have to depend on an external mechanism.

    So let's say you have initially created Bus A and B. When you call A.setNext( B ), it should also update the previous node of B, without having to call B.setPrevious( A ). Similar as when you add something to a LinkedList in Java, you do not have to manually set the link between the last object and the object you just added. Something like

    public void setPrevious(Bus bus) {
      this.previous = bus;
      if ( bus.next != this ){
        bus.next = this;
      }
    }
    

    Of course then you still have to consider the scenario where the bus is already contained in another List that you have to update that List as well.

    Therefore, the suggestion to separate the nodes from the actual bus instances as suggested in one of the other responses is a better idea. This allows you to add busses to multiple lists, and makes it probably easier to write your circular list (or just use an available implementation for the list). This is also better OO design as you can reuse the list you wrote.