Advertisement
eric11144

linked-list-insert

Jan 6th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4.  
  5. #include "push.h"
  6.  
  7. void
  8. linked_list_node_initialize(node_t *n)
  9. {
  10. assert(n != NULL);
  11. n->word = '\0';
  12. n->next = NULL;
  13. }
  14.  
  15. void
  16. linked_list_node_insert(node_t **sptr,
  17. char c)
  18. {
  19. assert(sptr != NULL);
  20. node_t *head = *sptr;
  21. assert(head != NULL && "Please pass a pointer to a list node to me.");
  22.  
  23. if(head->word == '\0' && head->next == NULL)
  24. {
  25. head->word = c;
  26. return;
  27. }
  28. node_t *cur = head;
  29. node_t *last = NULL;
  30. node_t *to_insert = NULL;
  31.  
  32. to_insert = (node_t*)malloc(sizeof(node_t));
  33. linked_list_node_initialize(to_insert);
  34. to_insert->word = c;
  35.  
  36. while(cur != NULL)
  37. {
  38. last = cur;
  39. cur = cur->next;
  40. }
  41. printf("original last character is: %c\n", last->word);
  42. last->next = to_insert;
  43. }
  44.  
  45. void
  46. linked_list_printlist(node_t *sptr)
  47. {
  48. assert(sptr != NULL);
  49. node_t *cur = sptr;
  50. printf("linked_list_printlist: ");
  51. while(cur != NULL)
  52. {
  53. printf("%c", cur->word);
  54. // ternary operator ?:
  55. printf((cur->next == NULL) ? "\n" : " ");
  56. cur = cur->next;
  57. }
  58. // do some works
  59. }
  60.  
  61. char linked_list_node_all_delete(node_t **sptr)
  62. {
  63. node_t *current, *head;
  64. head = *sptr;
  65. while( head != NULL)
  66. {
  67. current = head;
  68. head = current->next;
  69. free(current);
  70. }
  71. if(head == NULL)
  72. {
  73. printf("node is empty \n");
  74. }
  75. }
  76.  
  77. int main()
  78. {
  79. char a = 'a';
  80. node_t *s = malloc(sizeof(node_t));
  81. linked_list_node_insert(&s, a);
  82. linked_list_node_insert(&s, a);
  83. //linked_list_node_insert(&s, a);
  84. linked_list_printlist(s);
  85. linked_list_node_all_delete(&s);
  86.  
  87. return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement