Advertisement
encoree1996

lista

Jun 25th, 2016
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5. #define N 10
  6.  
  7. typedef struct _list
  8. {
  9.     struct _list *next;
  10.     int value;
  11. }LIST;
  12.  
  13. void list_insert(LIST** head, int val)
  14. {
  15.     if(*head != NULL)
  16.     {
  17.         LIST* tmp = *head;
  18.         while(tmp->next != NULL)
  19.             tmp = tmp->next;
  20.         tmp->next = calloc(1,sizeof(LIST));
  21.         tmp->next->value = val;
  22.     }else
  23.     {
  24.         *head = calloc(1,sizeof(LIST));
  25.         (*head)->value = val;
  26.     }
  27. }
  28.  
  29. void list_print(LIST* head)
  30. {
  31.     LIST* tmp = head;
  32.     printf("List contents: ");
  33.     while(tmp->next != NULL)
  34.     {
  35.         printf("%d ",tmp->value);
  36.         tmp = tmp->next;
  37.     }
  38.     printf("%d \n", tmp->value);
  39. }
  40.  
  41. void list_dellast(LIST* head)
  42. {
  43.     LIST* tmp = head, *prev;
  44.     do
  45.     {
  46.         prev = tmp;
  47.         tmp = tmp->next;
  48.     }while(tmp->next != NULL);
  49.  
  50.     free(tmp);
  51.     prev->next = NULL;
  52. }
  53.  
  54. int list_len(LIST* head)
  55. {
  56.     LIST* tmp = head;
  57.     int l = 0;
  58.     while(tmp != NULL)
  59.     {
  60.         l++;
  61.         tmp = tmp->next;
  62.     }
  63.     return l;
  64. }
  65.  
  66. void list_middleinsert(LIST* head, int val)
  67. {
  68.     int pos = list_len(head)/2, i;
  69.     printf("\nInsert position found at %d\n",pos);
  70.     LIST* tmp = head;
  71.     for(i=1;i<pos && tmp != NULL;i++,tmp=tmp->next);
  72.     LIST* new_elem = calloc(1,sizeof(LIST));
  73.     new_elem->next = tmp->next;
  74.     tmp->next = new_elem;
  75.     new_elem->value = val;
  76. }
  77.  
  78. void list_free(LIST* head)
  79. {
  80.     LIST* tmp = head, *tmp2;
  81.     while(tmp->next != NULL)
  82.     {
  83.         tmp2 = tmp->next;
  84.         free(tmp);
  85.         tmp = tmp2;
  86.     }
  87.     free(tmp);
  88. }
  89.  
  90. int main()
  91. {
  92.  
  93.     srand(time(NULL));
  94.  
  95.     int numbers[N], i;
  96.     for(i=0;i<N;i++)numbers[i] = rand()%100;
  97.  
  98.     LIST* lista = NULL;
  99.  
  100.     for(i=0;i<N;i++)
  101.         list_insert(&lista,numbers[i]);
  102.  
  103.     printf("\nbefore: ");
  104.     list_print(lista);
  105.     printf("length = %d\n",list_len(lista));
  106.     list_middleinsert(lista,2137);
  107.     printf("\nafter: ");
  108.     list_print(lista);
  109.     printf("length = %d\n",list_len(lista));
  110.  
  111.     list_free(lista);
  112.  
  113.     return 0;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement