Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //MATHSPHYSIC CODE
- //LET CREATE SIMPLE LINKED LIST FROM SCRATCH
- //STEP 0: INCLUDE LIBRARY
- #include <stdio.h> //printf to use
- #include <string.h> //strcpy function from here
- #include <stdlib.h> //malloc & free
- #define MAX_SIZE 25
- //STEP 1: CRETE STRUCT NODE (SILPMY CREATE LIST'S NODE AND LIST )
- //this is linked list node
- typedef struct s_node {
- char name[MAX_SIZE]; //our data here
- struct s_node *next; //to move to the next node (pointer to the next node)
- }t_node;
- //this is our linked list: linked list is simply pointer of our node
- typedef struct s_list {
- t_node *node_pointer;
- }t_list;
- //STEP 2: INITIALIZE LINKED LIST NODE
- t_node *new_node(const char name[]){ //name is the string to add to linked list
- t_node *node = (t_node*)malloc(sizeof(t_node));
- if(node == NULL) //always test if malloc failed
- return NULL;
- strcpy(node->name, name); // strcy = string copy function
- node->next = NULL; //null because we don't add this node to linked list yet
- return node;
- }
- //STEP 3: CREATE FUNCTION TO ADDA CONTENT TO THEM
- void addContent(t_list **head, const char name[]){
- t_node *node = new_node(name);
- if(node != NULL){
- if(!head || !*head || !(*head)->node_pointer){ //if list is empty
- (*head)->node_pointer = node;
- return ;
- }
- //if list is not empty, go to the end and add your content
- t_node *tmp = (*head)->node_pointer;
- while(tmp && tmp->next)
- tmp = tmp->next; //this means move to the next node
- tmp->next = node; //here at the end of list we add our data
- }
- }
- //STEP 4: DISPLAY RESULT AND THEN ...... DEALLOCATE MEMORY BY DESTROYING LIST
- void display(t_list *list){
- if(list == NULL)
- return;
- t_node *tmp = list->node_pointer;
- while(tmp){
- printf("[ %s ] ", tmp->name);
- tmp = tmp->next; //it is like i++ or i=i+1 in array loop
- }
- }
- void destroyList(t_list **list){
- if(list && *list){
- t_node *tmp;
- while ((*list)->node_pointer){
- tmp = (*list)->node_pointer;
- (*list)->node_pointer = tmp->next;
- free(tmp);
- }
- free(*list);
- list = NULL; //to avoid dangling pointer
- }
- }
- //STEP 5: THE MAIN FUNCTION TO TEST
- int main(){
- t_list *list = (t_list*)malloc(sizeof(t_list));
- if(list == NULL)
- return (-1);
- list->node_pointer = NULL; //we must set this pointer to null because no node yet
- //here are data to add
- const char *names[]= {"John", "Isabella", "Adriana", "kwassi", "Ruth", NULL};
- int i = -1;
- //let add all these datas
- while(names[++i])
- addContent(&list, names[i]);
- //display content now
- display(list);
- //destroy list to deallocate memory
- destroyList(&list);
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement