Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. typedef struct nodo {
  6.     int valore;
  7.     struct nodo *succ;
  8. }   nodo_t;
  9.  
  10. nodo_t *crea_lista();
  11. void stampa_lista(nodo_t *);
  12. int cerca_numero(nodo_t *);
  13. int validazione_input();
  14.  
  15. int main() {
  16.     nodo_t *testa;      /*variabile che punterà alla lista*/
  17.     int trovato;        /*variabile risultato*/
  18.        
  19.         srand(time(NULL));
  20.         testa = crea_lista();
  21.         stampa_lista(testa);
  22.         trovato = cerca_numero(testa);
  23.        
  24.             if (trovato)
  25.                 printf("Trovato!\n");
  26.             else
  27.                 printf("Non trovato!\n");
  28.            
  29.     return(0);
  30. }
  31.  
  32. nodo_t *crea_lista() {
  33.     nodo_t *p , *succ_p;
  34.     int dim = rand() % 10 + 1;
  35.    
  36.     p = (nodo_t *)malloc(sizeof(nodo_t));
  37.     p->valore = rand() % 100 + 1;
  38.     p->succ = NULL;
  39.     succ_p = p;
  40.         for(int i = 2 ; i <= dim ; i++) {
  41.             succ_p->succ = (nodo_t *)malloc(sizeof(nodo_t));
  42.             succ_p = succ_p->succ;
  43.             succ_p->valore = rand () % 100 + 1;
  44.             succ_p->succ = NULL;
  45.         }
  46.     return(p);
  47. }
  48.  
  49. void stampa_lista(nodo_t *testa) {
  50.     nodo_t *p = testa;
  51.    
  52.         printf("Lista: \n");
  53.         while (p != NULL) {
  54.             printf("%d\t" , p->valore);
  55.             p = p->succ;
  56.         }
  57.     return;
  58. }
  59.  
  60. int cerca_numero(nodo_t *testa) {
  61.     int ris, n;
  62.     nodo_t *p = testa;
  63.    
  64.         printf("\nDigita il numero da cercare:\n");
  65.         n = validazione_input();
  66.             while(p != NULL && ris != 1) {
  67.                 ris = (p->valore == n)? 1 : 0;
  68.                 p = p->succ;
  69.             }
  70. return(ris);
  71. }
  72.  
  73. int validazione_input() {
  74.     int numero, controllo, pulizia_buffer;
  75.    
  76.         do {
  77.             controllo = scanf("%d", &numero);
  78.             if (!controllo) {
  79.                 printf("Input non accettabile, prego reinserire!\n");
  80.                 while ((pulizia_buffer = getchar()) != '\n');
  81.             }
  82.         }
  83.         while (!controllo);
  84.        
  85.         while ((pulizia_buffer = getchar()) != '\n');
  86.        
  87.     return(numero);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement