Advertisement
Tankado95

Inserisce X prima dell'ultima occorrenza di Y

May 30th, 2015
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. /*Inserisce un elemento x prima dell'ultima occorrenza di y*/
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. struct el{
  7. int info;
  8. struct el* next;
  9. };
  10. typedef struct el ElementoDiLista;
  11. typedef struct el * ListaDiElementi;
  12.  
  13. void stampa(ListaDiElementi l){
  14.  
  15.     while(l->next!=NULL)
  16.     {
  17.         printf("%d\n", l->info);
  18.         l=l->next;
  19.     }
  20. }
  21.  
  22.  
  23. void inserisci (ListaDiElementi *l, int x,int y){
  24. ListaDiElementi corr=*l, prec=NULL, new=malloc(sizeof(ElementoDiLista)), save=NULL;
  25. new->info=x;
  26. new->next=NULL;
  27. int trovato=0;
  28.  
  29.     if (*l!=NULL){
  30.         while(corr->next!=NULL){
  31.             if (corr->info==y){
  32.                 save=prec;
  33.                 trovato=1;
  34.             }
  35.             prec=corr;
  36.             corr=corr->next;
  37.         }
  38.         if (trovato==1){
  39.             if (save==NULL){
  40.                 new->next=*l;
  41.                 *l=new;
  42.             }
  43.             else {
  44.             new->next=save->next;
  45.             save->next=new;
  46.             }
  47.         }
  48.     }
  49.     else {
  50.         prec->next=new;
  51.     }
  52. }
  53.  
  54.  
  55.  
  56.  
  57. int main(){
  58. ListaDiElementi l=malloc(sizeof(ElementoDiLista));
  59. ListaDiElementi corr=l;
  60. int x=4,y=7,n=0;
  61. int i=0;
  62.     while(i<10)
  63.     {
  64.         scanf("%d",&n);
  65.         corr->info=n;
  66.         corr->next=malloc(sizeof(ElementoDiLista));
  67.         corr=corr->next;
  68.        
  69.         i++;
  70.     }
  71. corr->next=NULL;
  72. inserisci (&l,x,y);
  73. stampa(l);
  74. return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement