Obtaining Direct Access to a Linklist Class’ Elements

Environment: VC6

Well, all of you must know the MFC CList Class. I was having trouble using it so I made my own class and thought I would share it with you. The problem with the MFC class is that it does not provide direct access to individual elements of the list and sometimes you really need that facility.

This class is quite simple. Just add the LinkList.h file into your project. Make an instance of it, which will be your Linked List. Then add an element to the head or tail just as it was done using CList. Here’s an example:


CLinkList < CString > MyList; // Your LinkList Object
// containing CStrings as
// its elements.

MyList.AddHead(.M.); // Adds CString With data .M. to
// the head of your Link
// List.

MyList.AddHead(.YaZiR.); // Adds CString With data .YaZiR.
// to the head of your
// Link List.

MyList.AddTail(.Aheer.); // Adds CString With data .Aheer.
// to the tail of of your
// Link List.

Accessing the individual elements is quite simple. I have defined Element as a member of the CLinklist class, which you would use to access the elements. Initially, it is a NULL pointer. Use the specimen loop given below.


MyList.Element = MyList.Head; // Or MyList.Tail;
for(int i = 0 ; i < MyList.GetTotal() ; i++ )
{
//……………
// Use MyList.Element to work on elements
//…………..

MyList.Element = MyList.GetNext(); // Or MyList.GetPrev();
}

Well, that is all thare is to it. Feel free to use this code as it is or modify it as you like. Have fun.

Downloads

Download source – 1 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read