Witam. Próbuję od niedawna zrozumieć listy jednokierunkowe. Program się kompiluje, ale działa tylko w przypadku, gdy elementy dodawane są tylko na początek. Nie mam pojęcia, w którym miejscu popełniam błąd.
Oto kod:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct lista {
int numer;
char nazwa[10];
struct lista *next;
};
void dodaj_na_poczatek(struct lista **, int, char *);
void dodaj_na_koniec(struct lista *wsk, int wart, char * txt);
void wyswietl(struct lista *);
void zwolnij (struct lista *);
int main(void)
{
struct lista *head = NULL;
int numer,wybor,wybor2;
char tekst[10];
printf("Jesli chcesz dodac kolejny element do listy wpisz 1\n");
scanf("%d", &wybor);
while (wybor == 1)
{
printf("Podaj numer\n");
scanf("%d", &numer);
printf("Podaj nazwe\n");
scanf("%s", tekst);
printf("Dodac na poczatek, czy na koniec? 1 - poczatek, 2 - koniec\n");
scanf("%d", &wybor2);
if (wybor2 == 1)
dodaj_na_poczatek(&head,numer,tekst);
else if(wybor2 == 2)
dodaj_na_koniec(head,numer,tekst);
else
{
("Podales zla wartosc, koniec\n");
exit(-1);
}
printf("Jesli chcesz dodac kolejny element do listy wpisz 1\n");
scanf("%d", &wybor);
}
wyswietl(head);
zwolnij(head);
return 0;
}
void dodaj_na_poczatek(struct lista **wsk, int wart, char * txt)
{
struct lista *nowy;
nowy = (struct lista *) malloc (sizeof(struct lista));
if (!nowy)
{
printf("Przydzial pamieci nie powiodl sie\n");
exit(-1);
}
nowy->numer = wart;
strcpy(nowy->nazwa,txt);
nowy->next = NULL;
if (!*wsk)
*wsk = nowy;
else
{
nowy->next = *wsk;
*wsk = nowy;
}
}
void dodaj_na_koniec(struct lista *wsk, int wart, char * txt)
{
struct lista *nowy, *wsk1;
nowy = (struct lista *) malloc (sizeof(struct lista));
nowy->next = NULL;
nowy->numer = wart;
strcpy(nowy->nazwa,txt);
if(!nowy)
{
printf("Przydzial pamieci nie powiodl sie \n");
exit(-1);
}
if (!wsk)
wsk = nowy;
else
{
while(wsk1->next != NULL)
wsk1 = wsk1->next;
wsk1->next = nowy;
}
}
void wyswietl(struct lista *wsk)
{
struct lista *nowy;
nowy = wsk;
if (nowy == NULL)
printf("Brak elementow do wyswietlenia\n");
else
{
while (nowy != NULL)
{
printf("%3d %s \n", nowy->numer, nowy->nazwa);
nowy = nowy->next;
}
}
}
void zwolnij (struct lista *wsk)
{
struct lista *nowy;
while(nowy != NULL)
{
nowy = wsk;
free(nowy);
wsk = wsk->next;
}
}