简体   繁体   中英

How to count number of elements in a doubly-linked list?

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.

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;
}

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.

Try this.

int i=0;
if(first!=0){
    ++i;
    while(first!=last){
        first=first->next;
        ++i;
    }
}
std::cout<<i<<std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM