Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- // creo una struttura autoreferenziante
- //
- struct node{
- int data;
- struct node *next;
- };
- typedef struct node Node;
- typedef Node *List;
- // List e' &Node
- // perche' *List e' Node
- void printList(List head){
- printf("Lista collegata: \n");
- while((head -> next) != NULL){
- printf("%d\n",(head -> data));
- head = (head -> next);
- }
- printf("-----------------\n");
- }
- void headInsert(List *phead, int val){
- List new;
- // abbiamo creato un puntatore al nodo nuovo (Node *new)
- new = malloc(sizeof(Node));
- // malloc crea un puntatore (di tipo void*), conversione implicita.
- // abbiamo allocato sizeof(Node) byte, e il suo puntatore e' new!
- // ORA DOBBIAMO CONTROLLARE IL SUCCESSO DI MALLOC
- if (new != NULL){
- printf("Memory allocation successful!\n");
- (new -> next) = *phead;
- *phead = new;
- (new -> data) = val;
- }
- else
- printf("Unable to allocate dynamically memory!\n");
- }
- List search(List head,int val){
- int found = 0;
- while((head -> next) != NULL){
- if ((head -> data) == val){
- printf("%d e' il valore cercato.\n",(head -> data));
- return head;
- }
- else{
- printf("%d non e' il valore cercato.\n",(head -> data));
- head = head -> next;
- }
- }
- }
- void destroy(List head){
- List temp = head;
- List deleting = NULL;
- while((temp -> next) != NULL){
- deleting = temp;
- temp = temp -> next;
- free(deleting);
- }
- head -> next = NULL;
- }
- void _nullifyNext(List *phead){
- (*phead) -> next = NULL;
- }
- void searchCascadeDestroy(List *phead, int val){
- List cascadeVal = search(*phead,val);
- // ho un puntatore all'elemento dal quale iniziare a cancellare tutto
- destroy(cascadeVal);
- _nullifyNext(&cascadeVal);
- }
- void clusterInsert(int n, int ins[n], List *phead){
- for(int i = 0;i<n;i++)
- headInsert(phead,ins[i]);
- }
- int main(){
- // abbiamo bisogno di un puntatore al primo nodo!
- // List e' &Node
- List head = malloc(sizeof(Node));
- if (head != NULL){
- head -> data = 0;
- head -> next = NULL;
- }
- else
- printf("Head not allocated!\n");
- headInsert(&head,1);
- headInsert(&head,2);
- headInsert(&head,3);
- printList(head);
- searchCascadeDestroy(&head,2);
- printList(head);
- int clust[3] = {4,5,6};
- clusterInsert(3,clust,&head);
- printList(head);
- destroy(head);
- printList(head);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement