Trying to connect two different types of structures to create linked lists
An answer to this question on Stack Overflow.
Question
I'm looking for a way to connect nodes created by different structures to make linked lists and things like that. I tried several ways but I was not able to. Can you help me?
Here is my code:
struct nodeA{
int somedata;
nodeA* next;
};
struct nodeB{
int someData;
nodeB* next;
nodeB* someAnotherNode;
};
int main(){
nodeA* A0 = new nodeA; //Just creating some nodes...
nodeA* A1 = new nodeA;
nodeA* A2 = new nodeA;
nodeB* B0 = new nodeB;
A0 -> next = A1; //I can connect these nodes
A1 -> next = A2; //in this way.
A2 -> next = B0; //but, I can't do that!
return 0;
}
Answer
Use classes and polymorphism:
class NodeA {
public:
int somedata;
NodeA* next;
};
class NodeB : public NodeA {
NodeB* someAnotherNode;
};
int main(){
NodeA* A0 = new NodeA; //Just creating some Nodes...
NodeA* A1 = new NodeA;
NodeA* A2 = new NodeA;
NodeB* B0 = new NodeB;
A0 -> next = A1; //I can connect these Nodes
A1 -> next = A2; //in this way.
A2 -> next = B0; //but, I *can* do that!
return 0;
}