Reputation: 31
This is how the list is laid out:
struct Node {
Node *next;
Node *prev;
T datum;
};
Node *first; // points to first Node in list, or 0 if list is empty
Node *last; // points to last Node in list, or 0 if list is empty
I have tried:
int i =0;
while(first->next)
{
i++;
}
but this does not seem right.
Upvotes: 0
Views: 3445
Reputation: 596
your function needs to loop over the list while updating the pointer to the current node. Something like this :
function getLen(head) {
var curNode = head;
var len = 0;
while (curNode)
len++;
curNode = curNode.next;
}
return len;
}
Upvotes: 1
Reputation: 18652
You can solve this by walking a pointer from node to node until the pointer is NULL. Count the number of times the pointer is non-NULL. The code required is very simple:
int list_size(const Node *ptr)
{
int size = 0;
while (ptr) {
size++;
ptr = ptr->next;
}
return size;
}
Use it like so:
int size = list_size(first);
This code doesn't use the prev
pointer so it would also work for a singly-linked list.
Upvotes: 1
Reputation: 1294
Try this.
int i=0;
if(first!=0){
++i;
while(first!=last){
first=first->next;
++i;
}
}
std::cout<<i<<std::endl;
Upvotes: 0