Learning C
Learning C

Reputation: 689

Is this how I make a linked list within a linked list?

Well my project requires me for make a link list within a link list. Is it ok for me to define it this way?

struct users {
  int user_ID;

  struct playlist{
    int album;
    int track_num;
    struct playlist *next;
  }

  struct users *next;
};

Upvotes: 0

Views: 149

Answers (3)

tbert
tbert

Reputation: 2097

Yes, a linked list is a set of structs which have pointers to each other, so your solution is valid.

Point of order: when working with linked lists, it's really easy to fat-finger the code, or to forget a line, so write a set of functions/macros to do the list manipulation and always call those, so that you only have to get it right once.

Upvotes: 0

unwind
unwind

Reputation: 399833

Yes, it's absolutely fine to have struct members in structs, which is what you're doing.

Some find it nice to abstract out the "linked list" data, and just instantiate that whenever needed, but doing so might involve a need to cast.

Upvotes: 1

Martin Kristiansen
Martin Kristiansen

Reputation: 10222

Why not separate the structures?

struct Playlist{
    int album;
    int track_num;
    struct Playlist *next;
}


struct users {
  int user_ID;

  struct Playlist playlist 
  struct users *next;
};

it makes it easier to read, and easier to comprehend.

Upvotes: 1

Related Questions