RinoDrummer icon

Creazione di una Linked List

RinoDrummer | PRO | 09/16/17 04:09:56 PM UTC | 0 ⭐ | 317 👁️ | Never ⏰ | []
C |

1.13 KB

|

None

|

0 👍

/

0 👎

#include <stdio.h>
#include <stdlib.h>
 
struct Node {
    int val;
    struct Node *next;
};
 
struct Node *creaNodo(int val, struct Node *next);
struct Node *creaLista(struct Node *head, int n);
void stampaLista(struct Node *head);
 
int main(void) {
    int n;
    struct Node *lista = NULL;
    
    printf("Indicare quanti nodi formeranno la lista: ");
    scanf("%d", &n);
    
    lista = creaLista(lista, n);
    stampaLista(lista);
    
    system("pause");
}
 
struct Node *creaNodo(int val, struct Node *next) {
    struct Node *node = (struct Node *) malloc(sizeof(struct Node));
    
    node->val = val;
    node->next = next;
    
    return node;
}
 
struct Node *creaLista(struct Node *head, int n) {
    if (n >= 0) {
        if (head == NULL) {
            head = creaNodo(n, NULL);
        }
        
        head->next = creaLista(head->next, --n);
    }
    
    return head;
}
 
void stampaLista(struct Node *head) {
    if (head != NULL) {
        stampaLista(head->next);
        
        printf("Valore: %d;\n", head->val);
    }
    else {
        printf("\nCompletato.\n");
    }
}

Comments