fork download
  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. struct Node {
  7. char* value;
  8. struct Node* right_ptr;
  9. struct Node* left_ptr;
  10. };
  11.  
  12. // Create a new node
  13. struct Node* createNode(const char* str) {
  14. struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  15. if (!newNode) {
  16. printf("Memory allocation failed\n");
  17. exit(1);
  18. }
  19.  
  20. newNode->value = (char*)malloc(strlen(str) + 1);
  21. if (!newNode->value) {
  22. printf("Memory allocation failed\n");
  23. exit(1);
  24. }
  25.  
  26. strcpy(newNode->value, str);
  27.  
  28. newNode->left_ptr = NULL;
  29. newNode->right_ptr = NULL;
  30.  
  31. return newNode;
  32. }
  33.  
  34. // Append node to the end of the list
  35. void append(struct Node** head, const char* str) {
  36. struct Node* newNode = createNode(str);
  37.  
  38. if (*head == NULL) {
  39. *head = newNode;
  40. return;
  41. }
  42.  
  43. struct Node* temp = *head;
  44. while (temp->right_ptr != NULL) {
  45. temp = temp->right_ptr;
  46. }
  47.  
  48. temp->right_ptr = newNode;
  49. newNode->left_ptr = temp;
  50. }
  51.  
  52. // Print list forward
  53. void printForward(struct Node* head) {
  54. struct Node* temp = head;
  55. printf("Forward: ");
  56. while (temp != NULL) {
  57. printf("%s ", temp->value);
  58. temp = temp->right_ptr;
  59. }
  60. printf("\n");
  61. }
  62.  
  63. // Print list backward
  64. void printBackward(struct Node* head) {
  65. if (!head) return;
  66.  
  67. struct Node* temp = head;
  68. while (temp->right_ptr != NULL) {
  69. temp = temp->right_ptr;
  70. }
  71.  
  72. printf("Backward: ");
  73. while (temp != NULL) {
  74. printf("%s ", temp->value);
  75. temp = temp->left_ptr;
  76. }
  77. printf("\n");
  78. }
  79.  
  80. // Free memory
  81. void freeList(struct Node* head) {
  82. struct Node* temp;
  83. while (head != NULL) {
  84. temp = head;
  85. head = head->right_ptr;
  86. free(temp->value);
  87. free(temp);
  88. }
  89. }
  90.  
  91. int main() {
  92. struct Node* head = NULL;
  93.  
  94. // 7 char* values
  95. const char* data[7] = {
  96. "Node1", "Node2", "Node3", "Node4",
  97. "Node5", "Node6", "Node7"
  98. };
  99.  
  100. for (int i = 0; i < 7; i++) {
  101. append(&head, data[i]);
  102. }
  103.  
  104. printForward(head);
  105. printBackward(head);
  106.  
  107. freeList(head);
  108.  
  109. return 0;
  110. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Forward: Node1 Node2 Node3 Node4 Node5 Node6 Node7 
Backward: Node7 Node6 Node5 Node4 Node3 Node2 Node1