teaLeef
teaLeef

Reputation: 1989

Creating a linked list with different structure types

I am defining a linked list where on of the structure (the first one) has a different type from the others. This first node always exists.

Type1 -> Type2_1 -> Type2_2  -> Type2_3->etc

I must be able to rearrange the Type2 elements. For example, I can have:

Type1 -> Type2_3 -> Type2_1 -> Type2_2 -> etc

The way I am trying to do this is by defining a double linked list. Each Type2 element can point to the next Type2, the previous and, if need be the Type1. If the Type2 element is next to the Type1, then its pointer to the previous Type2 is set to NULL.

 typedef struct Type2{
        struct Type2 *next;
        struct Type2 *previous;
        int isNextToType1;
    } Type2;

Is there any better way to do this?

Upvotes: 0

Views: 109

Answers (1)

Drax
Drax

Reputation: 13278

typedef struct Type2
{
  ...
  struct Type2 *previous; // This is NULL for the first element
  struct Type2 *next; // This is NULL for the last element
} Type2;

typedef struct Type1
{
  ...
  struct Type2* list; // This might be NULL if the list is empty
} Type1;

Seems like you don't need anything more than this.

Upvotes: 2

Related Questions