Non era poi così difficile!!Il codice sensibile è nella funzione FlipList, il resto è brodo.
codice:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int el;
struct Node *next;
};
typedef struct Node Node;
void * myalloc(int n);
Node *ListCreate(Node *head,int el); //inserisce in coda
Node* FlipList(Node *head,Node* prev);
void PrintList(Node *head);
int main()
{
Node *head = NULL;
int v[10]={8,-5,-7,2,0,6,33,5,-45,-12},i,n=10;
for(i=0;i<n;i++)
{
head=ListCreate(head,v[i]);
}
printf("\n\nLista : ");
PrintList(head);
printf("\n\nLista invertita: ");
head = FlipList(head,NULL);
PrintList(head);
fflush(stdin);
getchar();
return 0;
}
void * myalloc(int n)
{
void * p=malloc(n);
if(!p)
{
printf("Memoria insufficiente!!");
exit(1);
fflush(stdin);
getchar();
}
return p;
}
Node *ListCreate(Node *head,int el)
{
//inserisce in coda
Node * p=(Node*)myalloc(sizeof(Node)),*t;
p->el=el;
p->next=NULL;
t=head;
if(!t) return p;
while(t->next) t=t->next;
t->next=p;
return head;
}
void PrintList(Node *head)
{
while(head)
{
printf("%d ",head->el);
head=head->next;
}
}
//Come vedi non era impossibile!!!
Node* FlipList(Node *head,Node* prev)
{
Node *p;
if(!head)
{
return prev;
}
p = FlipList(head->next,head);
head->next = prev;
return p;
}