Joe Joe - 4 months ago 25
Java Question

element at index in a circular linked list

I was reading about circular linked lists. Here is a code which I do not understand how it works.

public int elementAt(int index){
if(index>size){
return -1;
}
Node n = head;
while(index-1!=0){ // this line is unclear for me
n=n.next;
index--;
}
return n.data;
}


I would write the same code but in this way :

public int elementAt(int index){
if(index>size){
return -1;
}
Node n = head;
while(n.size != index){ // here is my change in the code
n=n.next;
}
return n.data;
}


Here is the whole code : http://algorithms.tutorialhorizon.com/circular-linked-list-complete-implementation/

Am I doing right in the second code ?

Thanks

Answer

it is just doing a count. You can do it in various way. I assume that the size is the size of your LinkedList. In that case your code is wrong. you can do like following

public int elementAt(int index){
        if(index>size){
            return -1;
        }
        Node n = head;
        int i = 0; // zero-indexing
        while(i++ != index){ // you can increment i at the end too
            n=n.next;
        }
        return n.data;
    }

FIrst code is also counting, but instead of using another variable it used the existing one