Guest User

Untitled

a guest
Jan 24th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include "./list.h"
  5.  
  6. int main(int argc, char *argv[]) {
  7. int arr[] = {1,2,3,4};
  8. List *list = createList();
  9. int i = 0;
  10. for(i = 0; i < 4; i++) {
  11. appendList(list, arr[i]);
  12. }
  13. return 0;
  14. }
  15.  
  16. List *createList() {
  17. List *list = malloc(sizeof(List));
  18. if(list == NULL) {
  19. return NULL;
  20. }
  21.  
  22. list->head = malloc(sizeof(Node));
  23. list->tail = malloc(sizeof(Node));
  24. if(list->head == NULL || list->tail == NULL) {
  25. free(list);
  26. return NULL;
  27. }
  28.  
  29. list->size = 0;
  30. return list;
  31. }
  32.  
  33. void appendList(List *list, int num) {
  34. if(list->head->value == 0) {
  35. list->head->value = num;
  36. list->tail->value = num;
  37. return;
  38. }
  39. Node *current = calloc(1, sizeof(Node));
  40. current = list->head;
  41. while(current->next != NULL) {
  42. current = current->next;
  43. }
  44. current->next = calloc(1, sizeof(Node));
  45. if(current->next == NULL) {
  46. free(current->next);
  47. printf("Failed to allocate memory");
  48. exit(1);
  49. }
  50. current->next->value = num;
  51. list->size += 1;
  52. list->tail = current->next;
  53. }
  54.  
  55. #ifndef List_h
  56. #define List_h
  57.  
  58. #include <stdlib.h>
  59.  
  60. typedef struct node {
  61. int value;
  62. struct node *next;
  63. } Node;
  64.  
  65. typedef struct {
  66. Node *head;
  67. Node *tail;
  68. int size;
  69. } List;
  70.  
  71. List *createList();
  72. void appendList(List *, int num);
  73. Node *removeList(List *);
  74. void printList(List *);
  75.  
  76. #endif
Add Comment
Please, Sign In to add comment