Intersezione insiemistica liste

#include < stdio.h >
#include < stdlib.h >

/* definisco la struttura */
struct nodo
{
int elem;
struct nodo * next;
};

typedef struct nodo L_ELEM;
typedef struct nodo * L_PTR;

void stampa_lista(L_PTR p);
L_PTR inserisci_in_coda(L_PTR L, int val);
void intersezione(L_PTR L1, L_PTR L2, L_PTR *L3);

int main()
{
L_PTR startPtr = NULL ;
L_PTR startPtr2 = NULL;
L_PTR startPtr3 = NULL;
int k=0;
int w=0;
int val=0;
int z=0;
int y=0;
scanf("%d",&k);
z=k;
while(k>0)
{
scanf("%d",&val);
startPtr = inserisci_in_coda(startPtr, val);
k--;
}

scanf("%d",&w);
y=w;
while (w>0)
{
scanf("%d",&val);
startPtr2 = inserisci_in_coda(startPtr2, val);
w--;
}
intersezione(startPtr,startPtr2,&startPtr3);
stampa_lista(startPtr3);
return 0;
}

void stampa_lista(L_PTR p) {
while (p != NULL) {
printf("%d ", (p)->elem);
p = (p)->next;
}
return;
}

L_PTR inserisci_in_coda(L_PTR L, int val)
{
L_PTR curr,temp;
curr=L;
temp = malloc(sizeof(L_ELEM));

if(temp != NULL)
{
temp->elem = val;
if (L==NULL)
{
temp->next = NULL;
curr=temp;
}
else
{
while(L->next != NULL )
L=L->next;
temp->next=L->next;
L->next= temp;
}
return curr;
}
else return NULL;
}

void intersezione(L_PTR L1, L_PTR L2, L_PTR *L3)
{

if (L1==NULL && L2==NULL) return;

if (L1==NULL) // se L1 e' una lista vuota non succede nulla
{
return;
}
if (L2==NULL) // lo stesso se L2 e' vuota
{
return;
}
if (L1->elem == L2->elem) // metto in L3 l'elemento di L1 (o L2) e mando avanti entrambe le liste
{
*L3 = L1;
intersezione(L1->next,L2->next,&(*L3)->next);
return;
}
if (L1->elem < L2->elem) // mando avanti L1
{
intersezione(L1->next,L2,&(*L3));
return;
}else // altrimento mando avanti L2
{
intersezione(L1,L2->next,&(*L3));
return;
}
}

Commenti