views:

70

answers:

5

Can someone 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();
}; 
A: 

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
dutt
A: 

int size() { return count; }

Greg Domjan
A: 

Something like:

int Count()
{
    return count;
}
Andrew Cooper
A: 

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; 
}
Anders K.
Thanks Mr.Anders K.I used the method of adding ++count in inserthead and --count in Removehead.I made a function size which outputs count(size).
Salar
+2  A: 

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.

TokenMacGuy
+1 for elaborating on upside and downside.
JMP