Reputation: 3185
A small query really with reference to Structs.
If I had a
Struct Node {
char *number;
struct Node *next;
}List;
and a tree Structure:
struct Node {
char *name;
char *number;
struct Node *right;
struct Node *left;
};
and I wanted to design it, such that each Node within my Tree, can each contain a LIST of Phone Numbers, is there a way in which I can do this, and if so, how exactly can I reference my struct List within my Tree?
EDIT:
Any ideas as to why this is seg faulting? Using the Structs recommended below.
TreeNode* AddNode(TreeNode *root, ListNode *list, char *name, char *phonenum) {
int comparison;
if ( root == NULL ) {
root = (TreeNode *)malloc(sizeof(TreeNode));
list = (ListNode *)malloc(sizeof(ListNode));
root->name = strdup(name); root->list->number = strdup(phonenum);
root->left = root->right = NULL;
Upvotes: 1
Views: 551
Reputation: 32510
You'd simply do it like so:
typedef struct Node {
char* name;
List* list;
struct Node *right;
struct Node *left;
} Node;
Then in order to get a local copy of the first element of the list in each node, you'd do something like the following:
Node* treenode; //this is pointing to some node in the tree
char* num_buffer = strdup(treenode->list->number);
//use num_buffer and then call free() on it when you're finished
If you wanted to get a number that was not the first number in the list, you would have to create a search function for your linked list.
Upvotes: 2
Reputation: 272507
Can you do something like this?
typedef struct ListNode
{
char *number;
struct ListNode *next;
} ListNode;
typedef struct TreeNode
{
char *name;
ListNode *numbers;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
Upvotes: 1