Advertisement
Guest User

tristezza

a guest
Jan 14th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. /*Scrivere un programma che permetta di inserire un nuovo studente nella lista degli
  2.  * studenti universitari, in modo che tale lista semplicemente concatenata sia ordinata
  3.  * rispetto al numero di matricola. Stampare la lista.*/
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8.  
  9. typedef struct studente {
  10.     char nome[30];
  11.     char cognome[30];
  12.     int matricola;
  13.     struct studente *next;
  14. } studente;
  15.  
  16. studente *head=NULL;
  17.  
  18. studente* inseriscistud( studente* head, studente* stud);
  19.  
  20. void main() {
  21.     studente *stud=NULL;
  22.     stud=(studente*)malloc(sizeof(studente*));
  23.     studente *s; //puntatore per la stampa
  24.  
  25.     printf("Inserisci nome: ");
  26.     gets(stud->nome);
  27.     printf("Inserisci cognome: ");
  28.     gets(stud->cognome);
  29.     printf("Inserisci numero di matricola: ");
  30.     scanf("%d", stud->matricola);
  31.     head= inseriscistud(head, stud);
  32.     s=head;
  33.     while(s!=NULL) {
  34.         printf("Nome: %s\nCognome: %s\nMatricola: %d\n\n", s->nome, s->cognome, s->matricola);
  35.         s=s->next;
  36.     }
  37. }
  38.  
  39. studente* inseriscistud(studente *head, studente *stud) {
  40.     studente *r=NULL, *q=NULL;
  41.     studente *p=NULL;
  42.     if(head==NULL) {
  43.         head=(studente*)malloc(sizeof(studente*));
  44.         strcpy(head->nome, stud->nome);
  45.         strcpy(head->cognome, stud->cognome);
  46.         head->matricola= stud->matricola;
  47.         head->next= NULL;
  48.     }
  49.     else {
  50.         r=head; //precedente
  51.         q=head; //successivo
  52.         p=(studente*)malloc(sizeof(studente*));
  53.         strcpy(p->nome, stud->nome);
  54.         strcpy(p->cognome, stud->cognome);
  55.         p->matricola= stud->matricola;
  56.  
  57.         while((q!=NULL) && (q->matricola < p->matricola)) {
  58.             r=q;
  59.             q=q->next;
  60.         }
  61.         r->next= p;
  62.         p->next= q;
  63.         return p;
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement