Ho un nuovo problema: ho implementato una linked list unidirezionale alla quale rimuovo elementi dalla testa e ne aggiungo di nuovi in coda. Funziona tutto bene se creo una lista sola, mentre se ne creao una, la cancello e poi ne creo un'altra non capisco più cosa fa!Queste sono le funzioni:
typedef struct node
{
int x;
int y;
struct node* next;
} pNode;
void initList(int x, int y)
{
head = (pNode*)malloc(sizeof(pNode));
tail = (pNode*)malloc(sizeof(pNode));
if(head!=NULL)
{
head->x = x;
head->y = y;
}
else
{
printf("\nError while creating the list");
getchar();
exit(1);
}
tail = head;
}
// adds an element at the end of the list
void addNode(int x, int y)
{
pNode* toAdd = (pNode*)malloc(sizeof(pNode));
if(toAdd!=NULL)
{
tail ->next = toAdd;
toAdd->next = NULL;
toAdd->x = x;
toAdd->y = y;
tail = toAdd;
}
else
{
printf("\nError while adding the new node to the address %p", toAdd);
getchar();
exit(1);
}
}
// removes the first element of the list
void removeHead( )
{
pNode* toDelete = head;
if(toDelete->next==NULL)
{
printf("\nThe list is empty");
head = NULL;
}
else
head = toDelete->next;
free(toDelete);
}
void printList()
{
int i=1;
pNode* tmp = head;
printf("\n\nPRINTING THE LIST\n");
while(tmp!=NULL)
{
printf("\nThe %dth element is: x:%d y:%d", i++, tmp->x, tmp->y);
tmp = tmp->next;
}
printf("\n");
}
void freeList()
{
pNode* tmp = head;
while(tmp!=NULL)
{
free(tmp);
tmp = tmp->next;
}
}
Il programma fa per prima cosa
initList(x, y);
poi una serie di addNode(x,y) e removeHead()
infine freeList().
A questo punto rifaccio il procedimento da capo.
In pratica sembra che la testa non venga mai cancellata...inoltre non ho la certezza che sia la lista la parte sbagliata, quindi vi chiedo se potete dare un occhio al codice e dirmi se è corretto! Grazie...
|