Na dzisiejszych zajęciach zajmiemy się usuwaniem elementów z pojedynczych list jak również usuwaniem całych list. I na początek takie proste zadanie. Popatrzmy, jak zaimplementować pseudokod programu, który by usunęła całą listę:

struct node *usunliste (struct node *l){

struct node *pom;

while (l !=NULL){

pom=l;

l=l->next;

free (pom);

}

}

I kolejne zadanie. Na ostatnich lebolatoriach implementowaliśmy funkcję dodającą na początek listy jakiś element. Dziś wykonamy zadanie, które doda jakiś element, ale na koniec listy, czyli jakby dołączy go na koniec. Popatrzmy, jak by wyglądała implementacja takiej struuktury:

struct node *dodaj (struct node *l, int w){

struct node *e, *pocz=l;

struct node atrapa; // pierwszy element

atrapa.next=l; // podpiecie do listy

e=(struct node *) malloc (sizeof )struct node));

if (e=NULL) printf ("error");

else {

l=&atrapa; // wskazanie atrapy

e->val=w;

e->next=NULL;

if (l==NULL) // mozna usunac

pocz=e; // mozna usunac

else { // mozna usunac

while (l -> next != NULL)

l=l->next;

}

l->next=e;

}

return pocz;

return atrapa.next; // wskazanie poczatku

}

Ale istnieje jeszcze łatwiejsze rozwiązanie. A mianowicie:

struct node * dodaj (struct node * l, int w){

struct node *e, *pocz=l, *a;

struct node atrapa; // pierwszy element

a=&atrapa

a -> next=l; // podpiecie do listy

e= (struct node *) malloc (sizeof )struct node));

if (e=NULL) printf ("error");

else {

l=a; // wskazanie atrapy

e->val=w;

e->next=NULL;

if (l==NULL) // mozna usunac

pocz=e; // mozna usunac

else { // mozna usunac

while (l -> next != NULL)

l=l->next;

}

l->next=e;

}

return a -> next; // wskazanie poczatku

}

No i ostatnie z zadań. Ma ono na celu usunięcie elementu z listy z atrapą. Oto pseudokod:

struct node *usun (struct node *l, int w, int a){

struct node *e, *poprz;

struct atrapa; // atrapa

a=&atrapa; // wskazanie

if (l != NULL){ // w przypadku kiedy nie ma nic

if (l -> val == w){ // jesli pierwszy element jest 1

e=l;

l=l -> next;

free (e) // usun

}

else{

poprz=l;

poprz=a; // wskaz atrape

e=poprz.next;

while (e != NULL && e->val !=w){

poprz=e;

e=e -> next;

}

if (e !=NULL){

poprz ->next = e -> next;

free (e);

}

return l;

return a-> next;

}

}

}