I have this function called display
that shows the contents of my linked list from start to finish and I would like for it to go from finish to start when it is done.
I am trying to turn this singly linked list into a doubly linked list, but I am having trouble understanding just how *next
in this code knows to go to next, and how to make *prev
go to previous.
I tried to create a function called displayReverse
, but that did not work.
Does anyone have any advice? Thanks in advance
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// map number to name
const char *map[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
// data structure
typedef struct Data
{
int number;
char name[5];
} data_t;
// define the item (node) of a linked list
typedef struct Node
{
data_t data;
struct Node *next;
struct Node *prev;
} node_t;
// declare of functions
// add(node_t **, node_t) - it is function signature
void add(node_t **, node_t);
void print_node(node_t *);
void display(node_t **);
void freeList(node_t **);
int main(int argc, char const *argv[])
{
node_t *list = NULL; // the head of a linked list
for (int i = 0; i < sizeof(map) / sizeof(map[0]); ++i)
{
node_t node = { .data.number = i };
strcpy(node.data.name, map[i]);
add(&list, node);
}
puts("The linked list is: ");
display(&list);
freeList(&list);
return 0;
}
void add(node_t **head, node_t node)
{
node_t *tmp = (node_t *)malloc(sizeof(node_t));
tmp->data = node.data;
tmp->next = *head;
tmp->prev = *head;
*head = tmp;
}
void display(node_t **head)
{
node_t *ptr = *head;
while (ptr != NULL)
{
print_node(ptr);
ptr = ptr->next;
}
}
void freeListReverse(node_t **head)
{
node_t *tmp;
while (*head != NULL)
{
tmp = *head;
*head = (*head)->prev;
free(tmp);
}
}
void freeList(node_t **head)
{
node_t *tmp;
while (*head != NULL)
{
tmp = *head;
*head = (*head)->next;
free(tmp);
}
}
void print_node(node_t *node)
{
printf("node: %d, %s, len of name %ld; next: %p\n",
node->data.number, node->data.name, strlen(node->data.name), node->next);
}