开发者

size of linked list in c++ function

开发者 https://www.devze.com 2023-01-20 02:00 出处:网络
Can someo开发者_运维技巧ne please tell what is the code for checking the size of a linked list(number of nodes).This is what my code is(inserting nd deleting head + printing info of all nodes)

Can someo开发者_运维技巧ne please tell what is the code for checking the size of a linked list(number of nodes).This is what my code is(inserting nd deleting head + printing info of all nodes)

struct node 
{
    int info;
    node *nextptr;
};

class list
{
private:
    node *L,*tail;
     int count;

public:
    list()
    {
        L=tail=NULL;
        count=0;
    }

    void InsertHead(int info);
    int RemoveHead();
    void Print();
}; 


There are two ways to manage the size of a linked list, both have shortcomings. The simplest is to manage a count variable, your class has such a variable, and you increment it every time you add a node to the list, and decrement it every time you remove a node.

In this case, you can get the size of the linked list in constant time. The downside is that a useful operation, splice, where you take a list and cut it into two smaller lists somewhere in the middle, becomes linear complexity, because now you have to count how many nodes are in the sublists.

If you want splice to be constant, then you can't track the size of the lists. So any time you want to get the size of the list, you have to count how many nodes are there.


Well the simplest would beto add in the function InsertHead add ++count and in the RemoveHead do --count

Otherwise you could use a loop to go through the list

e.g.

node* p = L; 
while (p != NULL) 
{ 
  ++count; 
  p = p->nextptr; 
}


You need to create a counter and then loop through your list increasing the counter

pseudocode:

count = 0
iterator = head
while(iterator != 0)
    count++
    iterator = iterator.next


Something like:

int Count()
{
    return count;
}


Try this:

int size() { return count; }
0

精彩评论

暂无评论...
验证码 换一张
取 消