Reputation: 31
I have these structs in C:
typedef struct team{
char *name;
int wins;
} *pTeam;
typedef struct node_team{
pTeam team;
struct node_team *next;
} *link_team;
So I have various of these teams, and I'm putting them on a linked list, each element of the linked list is a link_team, so having 2 link_team's, A
and B
, if I want to put B
after A
, I do A->next=B
. However, I have 2 lists, and both lists share some of the same elements, and so if I have A
in both of them and want B
after A
in one list, I don't want it in the other list. However, since we're talking about pointers, and both lists have the pointer pointing to the struct A
, by doing A->next=B
in one list, B
is linked to A
automatically in the other list as well. How can I prevent this?
Upvotes: 1
Views: 43
Reputation: 6740
The next
pointers are what make the linked list a linked list. So, you couldn't mix the lists the way you're doing it. However, the only data a node contains besides the pointer to the next object is the pTeam
object. That can easily be shared across different lists (though you need to be careful).
... // Suppose you already have five pTeam pointers: p1, ..., p5
link_team *head1, *head2, *node1, *node2, *node3, *node4;
head1=malloc(sizeof(*link_team));
head2=malloc(sizeof(*link_team)); // I should be checking these return values but oh well.
head1->team=p1;
head2->team=p2;
node1=malloc(sizeof(*link_team));
node1->team=p3;
head1->next=node1;
node2=malloc(sizeof(*link_team));
node2->team=p3;
head2->next=node2;
node3=malloc(sizeof(*link_team));
node3->team=p4;
node3->next=NULL;
node1->next=node3;
node4=malloc(sizeof(*link_team));
node4->team=p5;
node4->next=NULL;
node2->next=node4;
Upvotes: 0