Kays
Kays

Reputation: 11

C singly linked list head points to another node's head

I know how to point a node's head to have either int value or a char value; however, I am stuck with how to point one node's head to another node's head.

For example, nodes head

Node "a"'s next points to another (f) node, whose head points to "b" and whose next points to node "d". I cant figure out how to allow node "f"'s head to point to node "b" and next points to "d". I wrote something like this, but its not working.

a->data = 'a';
a->next = f;

f->data = b;
f->next = d;

b->data = 'b';
b->next = c;

Upvotes: 0

Views: 152

Answers (2)

tstanisl
tstanisl

Reputation: 14157

consider using tagged union:

struct node {
    enum { NODE_CHAR, NODE_INT, NODE_NODE } tag;
    union {
        char c;
        int i;
        struct node *node;
    };
    struct node *next;
};

Now you can create a simple tree as:

// make a char node
struct node node0 = { .tag = NODE_CHAR, .c = 'a' };
// make it a predeccesor of `int` node
struct node node1 = { .tag = NODE_INT, .i = 42, .next = &node0 };
// make it a simbling of other char node
struct node node2 = { .tag = NODE_CHAR, .c = 'b' };
struct node node3 = { .tag = NODE_NODE, .node = &node2, .next = &node1 };

Upvotes: 0

Luca Polito
Luca Polito

Reputation: 2892

A possible solution:

struct node {
  char char_data;
  struct node* node_data;

  struct node* next;
};

So you have these nodes:

struct node* a = ...;
struct node* f = ...;
struct node* b = ...;
...

a->char_data = 'a';
a->node_data = NULL;
a->next = f;

f->node_data = b;
f->next = d;

b->char_data = 'b';
b->node_data = NULL;
b->next = c;

...

Practically, if node->node_data is NULL, it means that the node contains a char, so you read/set its node->char_data; if instead node->node_data is not NULL, it means that the node points to another node, so you ignore its node->char_data member, and instead you look at its node->node_data member.

Upvotes: 0

Related Questions