Search code examples
javadata-structureslinked-listcircular-list

I am trying to create a circular LinkedList Please tell me if its a correct way to do it


i have implemented logic like if i am giving a index that is not yet there then it will change the index to the reminder (Same like rotated i guess ).

import java.util.LinkedList;

public class MycircularlinkedList extends LinkedList {

    private static int count = 0;

    public Object get(int i) {
        System.out.println("count==" + count);
        if (i > count) {
            i = i % count;
            return super.get(i);

        } else {
            return super.get(i);
        }

    }

    public boolean add(Object o) {

        super.add(o);
        count++;
        return true;
    }

    public void add(int i, Object o) {
        if (i > count)
            i = i % count;
        super.add(i, o);
        count++;
    }
}

Solution

  • You're close.

    (1) The term "circular linked list" is well-known to mean a list where the tail links back to the head (and vice versa if it's a doubly-linked list). Yours is more like a "circular buffer" stored in a linked list. We could call it LinkedListCircularBuffer or something.

    (2) The class should be parameterized by the element type, thus

    public class LinkedListCircularBuffer<E> extends LinkedList<E> {
      @Override
      public E get(int i) {
        return super.get(i % size()); // simpler and faster without an "if"
      }
    }
    

    (3) You can call size() instead of all the code to maintain another count.

    (4) Your add(int i, Object o) method doesn't support the case where i == size(), but you can fix that by not overriding add() at all.

    (5) Overridden methods need the @Override annotation.

    (6) It's good style to always put braces around each "then" and "else" clause. Code like

    if (i > count)
      i = i % count;
    

    is fragile, e.g. adding a println() statement into that "then" clause will break it.