Advertisement
Tankado95

Sposta primo maggiore in fondo

Jun 2nd, 2015
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. /*Sposta il primo elemento maggiore di X in fondo alla lista*/
  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!=NULL)
  16.     {
  17.         printf("%d\n", l->info);
  18.         l=l->next;
  19.     }
  20. }
  21.  
  22.  
  23. void sposta(ListaDiElementi *l, int x){
  24. ListaDiElementi corr=*l, new=NULL, prec=NULL, save=NULL;
  25. int trovato=0;
  26.     while(corr->next!=NULL){
  27.         if (trovato==0){
  28.             if (corr->info>x ){
  29.                 trovato=1;
  30.                 new=malloc(sizeof(ElementoDiLista));
  31.                 new->info=corr->info;
  32.                 new->next=NULL;
  33.                 save=prec;
  34.                 }
  35.         }
  36.        
  37.                        
  38.             prec=corr;
  39.             corr=corr->next;
  40.            
  41.     }
  42. if (trovato==1){
  43.     if (save==NULL){
  44.         *l=(*l)->next;
  45.         prec->next=new;
  46.     }
  47.     else {
  48.        
  49.         prec->next=new;
  50.         save->next=save->next->next;
  51.        
  52.        
  53.     }
  54. }
  55. }
  56.  
  57.  
  58. int main(){
  59. ListaDiElementi l=malloc(sizeof(ElementoDiLista));
  60. ListaDiElementi corr=l;
  61. int x=4,n=0;
  62. int i=0;
  63.     while(i<10)
  64.     {
  65.         scanf("%d",&n);
  66.         corr->info=n;
  67.         corr->next=malloc(sizeof(ElementoDiLista));
  68.         corr=corr->next;
  69.        
  70.         i++;
  71.     }
  72. corr->next=NULL;
  73. sposta(&l, x);
  74. stampa(l);
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement