Witam !
Mam mały problem z algorytmem sito w liście ...
Otóż kompiluje się dobrze , nie wyskakuję błąd jedynie gdy wchodzi w funkcję odpowiadającą za ten algorytm po prostu zwiesza się.
Możliwe że jest tu jakiś drobny błąd , ale przeglądałem ten kod ze 4 razy i jakoś mi się go nie udało wychwycić . Może ktoś ma jakiś pomysł czemu to cudo nie działa ? Poniżej wklejam cały kod , a funkcja która sprawia problemy jest na końcu:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct prim
{
int x;
struct prim *next;
struct prim *prev;
};
typedef struct prim prim;
prim *head = NULL, *tail = NULL; //wskaźnik na glowe i ogon listy
//FUNCTIONS
//-------------------------------------------------------------------------
void add(int x); //dodaje liczbe do listy
void print(void);
void del(prim *trash); //przyjmuje wskaźnik do usunięci
void sito(int n); // przyjmuje zakres podany przez uzytkownika
//-------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int i;
int n;
print();
printf("\n\nPodaj Liczbe : ");
scanf("%d",&n);
for(i=2; i<n; i++)
add(i);
print();
sito(n);
printf("\n------------------------------------\n");
fflush(stdin);
print();
return 0;
}
void add(int x)
{
prim *nowy = NULL;
if(head == NULL)
{
head = tail = malloc(sizeof(prim));
head->x = x;
head->next = NULL;
head->prev = NULL;
return;
}
nowy = malloc(sizeof(prim));
nowy->x = x;
nowy->next = NULL;
nowy->prev = tail;
tail->next = nowy;
tail = nowy;
}
void print(void)
{
prim *tmp = head;
if(head == NULL)
{
printf("Lista jest pusta");
return;
}
while(tmp != NULL)
{
printf("%d\n",tmp->x);
tmp = tmp->next;
}
}
void del(prim *trash)
{
prim *tmp;
if(head == NULL)
{
printf("Lista jest pusta");
return;
}
else if(trash == head)
{
head->next->prev = NULL;
head = head->next;
free(trash);
return;
}
else if(trash == tail)
{
tail->prev->next = NULL;
tail = tail->prev;
free(trash);
return;
}
trash->prev->next = trash->next;
trash->next->prev = trash->prev;
free(trash);
}
void sito(int n)
{
prim *tmp = head, *tmp2 = head;
n = sqrt(n);
while(tmp->x < n); //Wykonuj dopóki Liczba będzie mniejsza od pierwiastka zakresu
{
tmp2 = head;
while(tmp2 != NULL) //Wykonuj dopóki wskaźnik tymczasowy tmp2 będzię różny od NULL , aby przejechać całą listę ;
{
if((tmp2->x % tmp->x) == 0) //Jeżeli liczba z listy jest podzielna przez któąś poprzednią
del(tmp2); //Wywal
tmp2 = tmp2->next;
}
tmp = tmp->next;
}
}