Advertisement
tinyevil

Untitled

Jan 8th, 2018
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define DEBUG(P) printf("%d\n", (P)->val);
  5. //Linked list.
  6. struct node {
  7. int val;
  8. struct node *next;
  9. };
  10.  
  11. void init_head(struct node **head) {
  12. (*head)->val = 0;
  13. (*head)->next = NULL;
  14. }
  15.  
  16. void add_first(struct node **head, int val) {
  17. struct node *node_t = (struct node *)malloc(sizeof(struct node));
  18. node_t->val = val;
  19. node_t->next = *head;
  20. *head = node_t;
  21. }
  22.  
  23. void add_last(struct node *head, int val) {
  24. struct node *ptr = head;
  25. while (ptr->next != NULL)
  26. ptr = ptr->next;
  27.  
  28. ptr->next = (struct node *)malloc(sizeof(struct node));
  29. ptr->next->val = val;
  30. ptr->next->next = NULL;
  31. }
  32.  
  33. void print_list(struct node *head) {
  34. struct node *ptr = head;
  35. while (ptr != NULL) {
  36. printf("Value: %d\n", ptr->val);
  37. ptr = ptr->next;
  38. }
  39. }
  40.  
  41. void delete_first_node(struct node **head) {
  42. struct node *ptr = *head;
  43. *head = ptr->next;
  44. free(ptr);
  45. }
  46.  
  47. void delete_last_node(struct node *head) {
  48. struct node *ptr = head;
  49. struct node *t = NULL;
  50. while (ptr->next != NULL) {
  51. t = ptr;
  52. ptr = ptr->next;
  53. }
  54. free(ptr);
  55. t->next = NULL;
  56. }
  57. void free_mem_list(struct node *head) {
  58. struct node *ptr_node;
  59. while ((ptr_node = head) != NULL) {
  60. head = head->next;
  61. free(ptr_node);
  62. }
  63. }
  64.  
  65. void remove_node(struct node **head, int _val) {
  66. struct node *ptr = *head;
  67. struct node *temp_ptr = ptr;
  68. while (ptr != NULL) {
  69. if (ptr->val == _val) {
  70. if (ptr == *head) {
  71. temp_ptr = *head;
  72. ptr = ptr->next;
  73. *head = (*head)->next;
  74. free(temp_ptr);
  75. temp_ptr = ptr;
  76. } else if (ptr->next == NULL) {
  77. delete_last_node(*head);
  78. return;
  79. } else {
  80. temp_ptr->next = ptr->next;
  81. free(ptr);
  82. ptr = temp_ptr->next; // RESTORE PTR , (IS THE RIGHT WAY(?))
  83. }
  84. }else{
  85. temp_ptr = ptr;
  86. ptr = ptr->next;
  87. }
  88. }
  89. }
  90.  
  91. int main(int argc, char **argv) {
  92. struct node *head = (struct node *)malloc(sizeof(struct node));
  93. init_head(&head);
  94. add_first(&head, 15);
  95. add_last(head, 13);
  96. add_last(head, 15);
  97. remove_node(&head, 15);
  98. print_list(head);
  99. free_mem_list(head);
  100.  
  101. return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement