devxlogo

Strange linked list

Strange linked list

Question:
How can I create a linked list that contains different datatypes? For example: assume that I have Human as a basic class. Man and Woman are two children to this class. How can I make a linked list that contains 10 men and 15 women?

Answer:
The easiest way is probably to place a pointer to your base class in each node of the linked list. This way, the pointer and nodes will always be the sames size, and only the data the pointer points to changes. Note that this approach requires you to allocate the memory to hold the class object as well.

Another approach you can take is to create a base class called CNode that has a next and, optionally, a previous pointer. You can then derive your Human class from CNode. This allows you to treat each item in the list as a CNode, even though each item will contain additional information.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist