CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2004
    Posts
    41

    finding the end of a list in C

    Hi I was hoping that some one could give me a hand with a bit of code I have a linked list and I am trying to count how many items are in the list could some one please heep me with a bit of code to do this.

  2. #2
    Join Date
    Sep 2002
    Location
    Belarus - Tirol, Austria
    Posts
    647

    Re: finding the end of a list in C

    Well, in case of non-circular linked list you have to iterate while the pointer to the next element != NULL.

    some C pseudo-code:

    Code:
    struct node {
            //data elements
            struct node *next;
            struct node *prev; // if this is a 2-way linked list
    };
    
    int size = 0;
    for (node *p = head; p; p = head->next, ++size);
    head is a list and size is a number of elements in it.

    if you have a circulary-linked list:

    Code:
    int size = 0;
    for (node *pos = (head)->next; pos != (head); pos = pos->next, ++size);
    "UNIX is simple; it just takes a genius to understand its simplicity!"

  3. #3
    Join Date
    Sep 2002
    Location
    14° 39'19.65"N / 121° 1'44.34"E
    Posts
    9,815

    Re: finding the end of a list in C

    Quote Originally Posted by Robbo99
    I have a linked list and I am trying to count how many items are in the list
    std::list has size() for that.

  4. #4
    Join Date
    Sep 2002
    Location
    Belarus - Tirol, Austria
    Posts
    647

    Re: finding the end of a list in C

    Quote Originally Posted by gstercken
    std::list has size() for that.
    The op has asked about C code, not C++. btw, I hope he didn't mean C++ saying C.
    "UNIX is simple; it just takes a genius to understand its simplicity!"

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured