Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define N 10
- typedef struct _list
- {
- struct _list *next;
- int value;
- }LIST;
- void list_insert(LIST** head, int val)
- {
- if(*head != NULL)
- {
- LIST* tmp = *head;
- while(tmp->next != NULL)
- tmp = tmp->next;
- tmp->next = calloc(1,sizeof(LIST));
- tmp->next->value = val;
- }else
- {
- *head = calloc(1,sizeof(LIST));
- (*head)->value = val;
- }
- }
- void list_print(LIST* head)
- {
- LIST* tmp = head;
- printf("List contents: ");
- while(tmp->next != NULL)
- {
- printf("%d ",tmp->value);
- tmp = tmp->next;
- }
- printf("%d \n", tmp->value);
- }
- void list_dellast(LIST* head)
- {
- LIST* tmp = head, *prev;
- do
- {
- prev = tmp;
- tmp = tmp->next;
- }while(tmp->next != NULL);
- free(tmp);
- prev->next = NULL;
- }
- int list_len(LIST* head)
- {
- LIST* tmp = head;
- int l = 0;
- while(tmp != NULL)
- {
- l++;
- tmp = tmp->next;
- }
- return l;
- }
- void list_middleinsert(LIST* head, int val)
- {
- int pos = list_len(head)/2, i;
- printf("\nInsert position found at %d\n",pos);
- LIST* tmp = head;
- for(i=1;i<pos && tmp != NULL;i++,tmp=tmp->next);
- LIST* new_elem = calloc(1,sizeof(LIST));
- new_elem->next = tmp->next;
- tmp->next = new_elem;
- new_elem->value = val;
- }
- void list_free(LIST* head)
- {
- LIST* tmp = head, *tmp2;
- while(tmp->next != NULL)
- {
- tmp2 = tmp->next;
- free(tmp);
- tmp = tmp2;
- }
- free(tmp);
- }
- int main()
- {
- srand(time(NULL));
- int numbers[N], i;
- for(i=0;i<N;i++)numbers[i] = rand()%100;
- LIST* lista = NULL;
- for(i=0;i<N;i++)
- list_insert(&lista,numbers[i]);
- printf("\nbefore: ");
- list_print(lista);
- printf("length = %d\n",list_len(lista));
- list_middleinsert(lista,2137);
- printf("\nafter: ");
- list_print(lista);
- printf("length = %d\n",list_len(lista));
- list_free(lista);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement