PDA

View Full Version : Generalized LinkedLists



hg_fs2002
July 2nd, 2010, 08:17 PM
Hi, I'm trying to implement Generalized linked lists and now I've got stuck somehow.
I want to write a function in order to add nodes to the last of a Generalized linkedlist with such a class. Is someone could help me or at least give me some tips.

class Gnode {
public:
int tag;
int flag;
char* data;
Gnode* link;
Gnode* dlink;
};

Gnode* link points to the horizontal nodes and Gnode* dlink points to the vertical nodes.

schauerlich
July 2nd, 2010, 08:48 PM
I assume this is C++? You should look into templates for a truly generic class. As for adding to the end of a linked list, the easiest way is to have a class ListNode, and another class List that consists of a pointer to the first and last elements of the list, and possibly other things like the count of elements, etc. Your methods would reside in that class too.

hg_fs2002
July 4th, 2010, 06:04 PM
Thanks a lot. Now I don't know how to store the string I've gotton from a getline function in the LinkedList when I'm calling my Add2Last function in main.I've written this:

class Gnode {
public:
int tag;
int flag;
char* data;
Gnode* link;
Gnode* dlink;
};
class Glist {
public:
Gnode* first1;
Gnode* first2;
public:
Glist () {
first1=new Gnode;
first2=new Gnode;
first1->link=NULL;
first1->dlink=NULL;
first2->link=NULL;
first2->dlink=NULL;
}
void Add2Last (constvoid *d);
};


void Glist::Add2Last (constvoid *d){
Gnode* l;
l=new Gnode;
Gnode* t;
t=new Gnode;
l->link=NULL;
l->dlink=NULL;
l->data=new char[strlen((char *)d)];
t=first2;
t->dlink=l;
l->tag=1;
l->flag=0;
t=t->link;
}

Now I gonna call my function in main,but I don't know how to match the argument of Add2Last function in main with the one I've written.

main (){
string s;
...........
.........
........
getline (f,s,' ');
D.Add2Last(s);
...........
...........
...........
}

schauerlich
July 5th, 2010, 04:45 AM
You're handing in a std::string object to a class that stores a char *. You either need to use templates like I said, use s.c_str() in main, or change your GNode class to store std::string's.

Also, please put your code in [code] tags.

dwhitney67
July 5th, 2010, 07:44 AM
If this is indeed C++, why not use the STL list?

For example:


#include <list>
#include <string>

struct NodeData
{
int tag;
int flag;
std::string data;
};

struct Gnode
{
std::list<NodeData*> link;
std::list<NodeData*> dlink;
};

class Glist
{
public:
Glist() {}
~Glist() { /* TODO */ }

void add2Last(const std::string& data);

private:
Gnode first1;
Gnode first2;
};


void
Glist::add2Last(const std::string& data)
{
NodeData* ndata = new NodeData;

ndata->data = data;
ndata->tag = 1;
ndata->flag = 0;

first2.link.push_back(ndata);
}


P.S. Some advice: avoid mixing C and C++, and avoid passing void data to functions.

schauerlich
July 5th, 2010, 07:45 AM
If this is indeed C++, why not use the STL list?

Because I'm 99% certain it's homework. :)