Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct node {
- int value;
- struct node * next; /* pointer to the same structure */
- } node;
- typedef node* list;
- /*
- * Assume that the list is in increasing order and insert the element
- * preserving the increasing order
- */
- list list_insert_ordered(list p, int val);
- /*
- * Concatenate two lists
- */
- list list_cat(list before, list after);
- /*
- * Insert elements at the head of the list
- */
- list list_insert_head(list p, int val);
- /*
- * Insert elements at the tail of the list
- */
- list list_insert_tail(list p, int val);
- /*
- * Print the list content
- */
- void list_print(list p);
- /*
- * Free the list
- */
- void list_free(list p);
- int main()
- {
- list head = NULL;
- /* insert some numbers in the list... */
- head = list_insert_head(head, 10);
- head = list_insert_head(head, 2);
- head = list_insert_head(head, 15);
- /* ... print them... */
- list_print(head);
- /* ... and clean everything up */
- list_free(head);
- /*...inserisci una lista di numeri ordinata in ordine crescente...*/
- head = list_insert_head(head, 10);
- //head = list_insert_head(head, 5);
- //head = list_insert_head(head, 2);
- /*inserisci un numero nella lista nella posizione giusta*/
- //head=list_insert_ordered(head,7);
- /*...stampala...*/
- list_print(head);
- /*...e cancellala*/
- //list_free(head);
- return 0;
- }
- list list_insert_head(list p, int val)
- {
- list new_el;
- /* Allocate the new node */
- new_el = malloc(sizeof(*new_el));
- /* Setting the data */
- new_el->value = val;
- /* head insertion: old head becomes .next field of new head */
- new_el->next = p;
- /* new head is the pointer to the new node */
- return new_el;
- }
- void list_print(list p)
- {
- /* Looping all nodes until p == NULL */
- if (p == NULL) {
- printf("Empty list\n");
- return;
- }
- printf("[%i]", p->value);
- for(; p->next!=NULL; p = p->next) {
- printf(" -> [%i]", p->next->value);
- }
- printf("\n");
- }
- void list_free(list p)
- {
- /* If p == NULL, nothing to deallocate */
- if (p == NULL) {
- return;
- }
- /* First deallocate (recursively) the next nodes... */
- list_free(p->next);
- /* ... then deallocate the node itself */
- free(p);
- }
- list list_insert_ordered(list p, int val){
- /*list new_el;
- new_el = malloc(sizeof(*new_el));
- new_el->value = val;*/
- if(p==NULL){
- /*new_el->next = p;
- return new_el;*/
- p->next=p;
- p->value=val;
- return p;
- }
- else if((p->value)>val){
- p->next->value=p->value;
- p->value=val;
- return p;
- }
- else{
- return list_insert_ordered(p->next,val);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement