You are here:

C++/data structures

Advertisement


Question
Hi,

How are you? Thank you very much for taking questions.
I am experimenting with linked lists and trees in C++. I think I know how to declare nodes for trees and also how to connect them with pointers. However, I only know how to do it one node at a time. My program needs to automatically make unknown number new nodes during runtime. How do you make automatic nodes without having to give each node an individual name. Is an array of nodes the way to go? Or is there another automatic naming pattern that Iím unaware of.

 Below is my code:

class MyTree
{
   int *id, *count;
   MyTree *left, *right;

 public:   
     
    MyTree(int a, int b)
      {
      id = new int; count = new int;   *id = a; *count = b;
      left = NULL;
      right = NULL;
      }
      
   ~MyTree(){delete id; delete count;}
   };

int main()
{

MyTree first_node(1,1);
MyTree second_node(2,1);
.
.
MyTree onehundredth_node(100,1);
}


How could I create code that doesnít need to know the names and numbers of the nodes beforehand.

My second question concerns FP-trees. Do you know of any implementation tutorials for FP-trees?

Sincerely,
         Andres


Answer
Linked lists are based on pointers.  In C and C++ every variable has a pointer associated with it.  You do not have to rename each pointer.  All you have to do is declare a variable as pointer:

int Variable ;
int * NextVariable ;

NextVariable = & Variable ;

Now to make this a linked list just add NextVariable to a structure and you can allocate as many of such structures as you need and link them together.  

There are different kinds of linked lists.  You can have a circular one where the to ends (beginning and end) of the linked list are also linked.  You can have a one directional one (e.g. traverse from beginning to end) or a two directional one (traverse from beginning to end and from end back to the beginning).  You can also have a tree of linked lists where a node may have more than one next node, etc.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.