Pointers & Linked Lists

I'm working on a Win32 Console Project and have run into a problem that hopefully someone can point me in the right direction.

Here's an idea of what is going on. Let's say I have a linked list class named "myList" and a node class "myNode", what I'm trying to do is now have a linked list of linked lists (so in effect, a list of myLists). Let call the list of lists by the class name of allLists.

I have the linked list and node implemented, each node containing a randomly generated number but I want to have a linked list of a so that I can manipulate a pointer that points to each list.

Here what it looks like:

List of nodes: [50]->[24]->[35]->[42]->[32] (myList)

List of Lists: (allLists)

[50]->[24]->[35]->[42]->[32] <= myPointer
[22]->[12]->[23]->[38]->[42]
[10]->[54]->[56]->[37]->[87]


This code is then implemented in the allList constructor (to create 3 myLists)
myList * r;

r = new myList * [3];

This does not seem to cause any problems with the compiler, but I can't figure out how to access each individual list and even further each individual node's integer value. I believe I'm doing this correctly but I haven't been able to find a solution to accessing the data.

Any help would be greatly appreciated!
Thanks,

CJ Loretz


Answer this question

Pointers & Linked Lists

  • steve17

    I agree that STL is better, especially in this case since the fact that std::vector is growable often makes it nice substitute for linked lists.  To go a little farther than Martin's suggestion, what you have looks like a "jagged array," where each row is of variable length.  You can further simplify your implementation with vector< vector< int> >.  Here's a little demo:

    #include <vector>
    #include <iostream>
    using namespace std;

    int main()
    {
       // Create jagged array
       vector< vector< int> > myJaggedArray;

       // Create three rows
       for( int r = 0; r < 3; r++ )
       {
          myJaggedArray.push_back( vector<
    int>() ); 
       }

       // Add a member to the third row
       myJaggedArray[ 2 ].push_back( 99 ); 

       // Iterate array, using for each, unique to VS2005.
       // (otherwise you can use a regular for loop
       // and use vector::size() to determine range.)
       for each( const vector<int>& row in myJaggedArray )
       {
          for each( int value in row )
          {
             cout << value << endl;
          }
       }

       return 0;
    }

    Brian

     


  • Robert McNeal

    A linked list is formed in a way like this.

    struct MYNODE {
    int data;
    MYNODE *next;
    };

    and an array of this list is something like this:

    MYNODE myListArray[3];

    But anyhow, think aboutusing the STL, it is much easier:

    typedef std::list<int> MYLIST;
    typedef std::vector<MYLIST> MYLISTARRAY;

    You can use push_back to easily add members to the list, and you can easily access the lists in the array.



  • Pointers & Linked Lists