Ćwiczę listy na takim kawałku kodu. Dodawanie elementów jest zapewne zrealizowane słabo, ale na razie sam to pisałem, bez patrzenia na cudzy kod. Działa usuwanie głowy, ale ogonu już nie. Domyślam się, że ma to związek ze zwracaniem zmiennej automatycznej mającej zasięg lokalny. Jak można inaczej napisać takie funkcje?
#include <stdio.h>
#include <stdlib.h>
struct ts
{
int key;
struct ts *prev, *next;
};
struct ts * push(struct ts * head, struct ts * x)
{
struct ts * temp = head;
if(head)
{
while(head->next != NULL)
{
head = head->next;
}
head->next = x;
x->prev = head;
}
else
{
return x;
}
return temp;
}
void wyswietl(struct ts * head)
{
while(head)
{
printf("%d\n", head->key);
head = head->next;
}
}
struct ts * usun_glowe(struct ts * head)
{
struct ts * temp = head;
if(head)
{
if(head->next != NULL)
{
head->next->prev = NULL;
free(head);
return temp->next;
}
else
{
free(head);
return NULL;
}
}
else
return NULL;
}
struct ts * usun_ogon(struct ts * head)
{
struct ts * temp = head;
if(head)
{
if(head->prev == NULL)
{
free(head);
return NULL;
}
else
{
head->prev->next = NULL;
free(head);
return temp;
}
}
else
return NULL;
}
int main(void)
{
struct ts *head = NULL, *x = NULL;
int i, n;
scanf("%d", &n);
for(i=1; i<=n; i++)
{
int a;
x = (struct ts *) malloc(sizeof(struct ts));
printf("Podaj wartosc dla wartosci %d \n", i);
scanf("%d", &a);
x->key = a;
x->prev = x->next = NULL;
head = push(head, x);
}
printf("Wyswietlenie listy:\n");
wyswietl(head);
head = usun_glowe(head);
printf("Wyswietlenie listy po usuniecu glowy:\n");
wyswietl(head);
head = usun_ogon(head);
printf("Wyswietlenie listy po usuniecu ogona:\n");
wyswietl(head);
return 0;
}