Reputation: 1
I've little problem with circular linkedlist : I want to insert an element (integer) at the end. My function add the element at the end but my linkedlist isn't really circular (I have this impression). this is .h with the structure I use:
struct liste_circulaire {
int val;
struct liste_circulaire *suivant; /* suivant = next element */
};
typedef struct liste_circulaire liste;
int main(void) {
liste *l, *deb;
deb = (liste *)malloc(sizeof(liste));
l = deb;
l -> suivant = deb; /* suivant = next element */
ajouter_element(l,0);
ajouter_element(l,1);
ajouter_element(l,2);
ajouter_element(l,3);
affiche(l,l->suivant);
printf("%d\n",l->suivant->suivant->suivant->suivant->suivant->val);
return 0;
}
void ajouter_element(liste *l,int x) {
liste *deb = l; /* with this line, I have a pointeur on the first element of my list */
while(l->suivant != deb) {
l = l -> suivant;
}
l -> suivant = (liste *)malloc(sizeof(liste));
l = l -> suivant;
l -> val = x;
l -> suivant = deb;
}
void affiche(liste *l,liste *deb) {
if(l == deb) {
printf(" Fin\n");
return;
}
printf(" %d -->",deb->val);
affiche(l,deb->suivant);
}
In my main, I have random number when I ask to print the first element of my list but in my example, the first value of my list in 0. So if anyone can to help me (I hope to be clear, I'm french student) Thank's !
Upvotes: 0
Views: 761
Reputation: 4344
Note that you never set the value of the first element. (Hernan just beat me here...)
When you call ajouter_element() it not only adds the new element to the end of the list, it sets the beginning of the list to be the new element:
l = l -> suivant;
affiche()
prints the second element first and the first element last. The first to be printed is deb->val
which in main would have been l->suivant->val
.
If you want affiche()
to print the first item... print it! :]
void affiche(liste *l,liste *deb) {
if (deb == 0)
{
deb = l;
}
printf(" %d -->",l->val);
if(l->suivant == deb) {
printf(" Fin\n");
return;
}
affiche(l->suivant,deb);
}
Call this with:
affiche(l,0);
or
affiche(l,l);
they'll both do the same thing. You could also overload it to take only the single value.
I haven't run this (or even compiled), but hopefully it's reasonably close.
Upvotes: 0
Reputation: 43518
you can use the predefined header file list.h
for circular linked list:
the following link contains an example of how to do it.
the list.h
contains all functions related to the management of a circular linked list like definition, add in the head , add in the tail , remove, foreach function to browse the circular linked list...
Upvotes: 1
Reputation: 2820
Your program is printing a random number because of this:
liste *l, *deb;
deb = (liste *)malloc(sizeof(liste));
l = deb;
l -> suivant = deb;
The first element in your list, is a node that you are allocating correctly but you are not giving any number. You should try adding:
l -> val = 0;
And getting rid of:
ajouter_element(l,0);
This should fix your problem.
Upvotes: 2