-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdata_structure.c
More file actions
84 lines (77 loc) · 2.07 KB
/
Copy pathdata_structure.c
File metadata and controls
84 lines (77 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "data_structure.h"
/**
* my own strdup function
*/
char *my_strdup(char *s) {
size_t len = strlen(s) + 1;
char *new_str = malloc(len);
if (new_str == NULL) return NULL;
return memcpy(new_str, s, len);
}
/**
* Creates a new Node for a linked list.
* Allocates memory for the Node, copies the id and content using strdup,
* sets the line index, and initializes the Next pointer to NULL.
* Returns the new Node or exits with an error if allocation fails.
*/
Node *create_Node(char *id, char *content, int line_index) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (!newNode) {
perror("ERROR: Memory allocation failed");
exit(1);
}
newNode->id = my_strdup(id);
newNode->content = my_strdup(content);
newNode->line_index = line_index;
newNode->Next = NULL;
return newNode;
}
/**
* Prints the content of each Node in the linked list.
* Traverses the list and prints the content of each Node.
*/
void printNodes(Node *mcro) {
Node *current = mcro;
while (current != NULL) {
printf("%s\n", current->content);
current = current->Next;
}
}
/**
* Adds a new Node to the end of the linked list.
* If the list is empty, the new Node becomes the head.
* Otherwise, it traverses the list to the end and appends the new Node.
*/
void add_to_node(Node **head, Node *new_node) {
if (!new_node) {
printf("Error: new_node is NULL\n");
return;
}
new_node->Next = NULL;
if (*head == NULL) {
*head = new_node;
} else {
Node *current = *head;
while (current->Next) {
current = current->Next;
}
current->Next = new_node;
}
}
/**
* Frees all memory allocated for the linked list.
* Traverses the list, freeing the id, content, and Node itself for each Node.
*/
void free_list(Node *head) {
while (head) {
Node *temp = head;
head = head->Next;
free(temp->id);
free(temp->content);
free(temp);
}
}