Mohd Hafiz - 1 month ago 4

Java Question

`public int size(){`

node n = head;

node m = tail;

int size = 0;

While(n!=m){

size++;

n=n.getNext();

}

return size;

}

Is this code correct? I'm not so sure and I'm asking for you guys opinion

Answer

The problem with your code logic is that you never check the last element of the list. Therefore, your `method`

will return the number of elements of the linked list minus one. To fix this, initialize `size`

to 1 instead of 0. And if you're concerned about linked lists of size 0, then use an if statement to check if the head or tail is null. Here's what it should look like,

```
public int size(){
node n = head;
node m = tail;
if(n == null){
return 0;
}
int size = 1;
While(n!=m){
size++;
n=n.getNext();
}
return size;
}
```

Source (Stackoverflow)

Comments