PDA

Click to See Complete Forum and Search --> : LIST question...


NOMADMAN
Mar 24th, 2002, 08:10 PM
My teacher gave us two of the classes we would need for this project, good thing too cause we're just beginners and this is heavy! Anyway, how do you get all the members out of your list, say in a FOR loop. I'm used to arrays and being able to call them by there index number... Whats up with the list class?

I'm not sure if you know what I'm tlaking about, not sure if its a standard data structure or not. If not I'll include the files, but you'd have too look through them and that would take some time I don't expect you to spend on this.

If by some chance you know what I'm talking about, and can offer a quick answer, please do! I'm out of ideas!

THANKS,

NOMAD!

CornedBee
Apr 2nd, 2002, 10:31 AM
You can't access a list by index. A list is SEQUENTIAL container, meaning that items are accessed only one after the next. Here is how you would access all items of a linked list (I didn't look at your source, so I'm using the invented data structures LIST and NODE which represent the linked list and a single node).
It is a single linked "loose end" list, because it has only the next node pointer.

// of course, this should be self-contained template classes
struct NODE
{
void* pData; // pointer to the stored data
NODE* pNext; // pointer to the next node.
};

struct LIST
{
NODE* pHead;
};

// a for loop to access all elements based on a list pointer:
void func(LIST* pList)
{
// a security measure:
assert(pList != NULL);
NODE* pNode;
for(pNode = pList->pHead; pNode != NULL; pNode = pNode->pNext)
{
// do whatever you want here
}
}