From b965e832b785f60d944d91a029a94e2bea9f0b9f Mon Sep 17 00:00:00 2001 From: mo khan Date: Sun, 5 Jul 2020 14:49:31 -0600 Subject: Extract a to_s function --- src/01/02b/doubly_linked_list.c | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) (limited to 'src/01') diff --git a/src/01/02b/doubly_linked_list.c b/src/01/02b/doubly_linked_list.c index 86fb1ce..cc18a71 100644 --- a/src/01/02b/doubly_linked_list.c +++ b/src/01/02b/doubly_linked_list.c @@ -1,6 +1,7 @@ #include "doubly_linked_list.h" #include #include +#include /** * The equivalent of a constructor @@ -136,18 +137,34 @@ void swap(Node *x, Node *y) { } /** - * Prints the previous, data and next pointers for a node + * Generates a string representation of the Node usable for printing to stdout * - * @param node The node to print + * @param node The node to represent as a string + * @return The string that represents the node */ -static void print(Node *node) { +char *to_s(Node *node) { + const int buffer_size = 32; + char *buffer = malloc(buffer_size); + memset(buffer, buffer_size, '\0'); + if (node->prev && node->next) - printf("(%d<%d>%d)", node->prev->data, node->data, node->next->data); + snprintf(buffer, buffer_size, "(%d<%d>%d) ", node->prev->data, node->data, node->next->data); else if (node->next) - printf("(nil<%d>%d)", node->data, node->next->data); + snprintf(buffer, buffer_size, "(nil<%d>%d) ", node->data, node->next->data); else - printf("(%d<%d>nil)", node->prev->data, node->data); - printf(" "); + snprintf(buffer, buffer_size, "(%d<%d>nil) ", node->prev->data, node->data); + return buffer; +} + +/** + * Prints the previous, data and next pointers for a node + * + * @param node The node to print + */ +static void print(Node *node) { + char *message = to_s(node); + printf("%s", message); + free(message); } /** -- cgit v1.2.3