Skip to content

Instantly share code, notes, and snippets.

@alexprivalov
Created January 31, 2015 18:36
Show Gist options
  • Save alexprivalov/196c02c30df07c5a3308 to your computer and use it in GitHub Desktop.
Save alexprivalov/196c02c30df07c5a3308 to your computer and use it in GitHub Desktop.
Write a “C” function to convert an array to a doubly-linked list.
#include <stdio.h>
#include <stdlib.h>
struct DoubleLinkedListItem //item of linked list
{
int field;
struct DoubleLinkedListItem *p_prev;
struct DoubleLinkedListItem *p_next;
};
struct DoubleLinkedListItem * converArrayToDoubleLinkedList(const arr[], size_t arr_size)
{
struct DoubleLinkedListItem *p_head = NULL;
do
{
struct DoubleLinkedListItem *p_current = NULL;
size_t i = 0;
if (arr_size <= 0) //simple check
{
printf("Warning: size of array equal or less 0!");
break;
}
for(; i < arr_size; i++)
{
struct DoubleLinkedListItem *p_item =
(struct DoubleLinkedListItem*)malloc(sizeof (struct DoubleLinkedListItem));
if (NULL == p_item) // simple check
{
printf("Some error occur during allocating, exit");
break;
}
p_item->field = arr[i];
if (NULL == p_current)
{
p_current = p_item;
p_current->p_prev = NULL;
p_current->p_next = NULL;
p_head = p_current;
} else
{
p_current->p_next = p_item;
p_item->p_prev = p_current;
p_item->p_next = NULL;
p_current = p_item;
}
}
} while(0); //usually I use 'false' in C++, but there is no bool type in C89
return p_head;
}
int main(int argc, char **argv)
{
int test_arr[] = {23, 32, 43, 54, 2, 86, 90};
int i = 0;
struct DoubleLinkedListItem *p_head = NULL;
printf("Before processing:\n");
for (; i < sizeof(test_arr)/sizeof(test_arr[0]); i++)
{
printf("%d ", test_arr[i]);
}
printf("\n");
p_head = converArrayToDoubleLinkedList(test_arr, sizeof(test_arr)/sizeof(test_arr[0]));
printf("After processing:\n");
if (NULL != p_head)
{
do
{
struct DoubleLinkedListItem *p_for_free = p_head;
printf("%d ", p_head->field);
p_head_2 = p_head->p_next;
free(p_for_free);
} while(p_head);
p_head = NULL;
} else
{
printf("empty linked list\n");
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment