Last active
March 31, 2017 21:28
-
-
Save iamthebot/1ddf64ee27d522abca44f2af44637a68 to your computer and use it in GitHub Desktop.
Array to Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*C++*/ | |
template<typename T> | |
struct ListNode { | |
next *ListNode = nullptr; | |
T data; | |
}; | |
template <typename T> | |
ListNode* vec_to_list(std::vector<T> array) { | |
ListNode* root = new ListNode; | |
current = root; | |
for(int i=0; i<array.size(); ++i) { | |
current->data = x; | |
if (i < array.size() - 1) { | |
current = current->next; | |
current->next = new ListNode; | |
} | |
} | |
return root; | |
} | |
/*C*/ | |
struct ListNode { | |
next *ListNode = nullptr; | |
void* data; | |
}; | |
ListNode* new_list_node(void* data, size_t size) | |
{ | |
ListNode root = malloc(sizeof(ListNode)); | |
if (!root) return NULL; //bad alloc | |
if (data) { | |
root->data = malloc(size); | |
if (!(root->data)) { free(root); return NULL;} //bad alloc | |
memcpy(root->data,data,size); | |
} | |
return root; | |
} | |
void free_list_node(ListNode* n) | |
{ | |
if (!n) return; | |
if (n->data) free(n->data); | |
free(n); | |
} | |
//array : pointer to array first element | |
//type_size: size of array element type in bytes | |
//len: number of elements in array | |
ListNode* array_to_list(void* array, size_t type_size, size_t len) { | |
ListNode* root = new_list_node(NULL,0); | |
ListNode* current = root; | |
for(int i=0; i<len; ++i) { | |
current->data = malloc(type_size); | |
if (current->data == NULL) return NULL; //bad alloc | |
memcpy(current->data, array,type_size); | |
if (i < len - 1) { | |
current-> next = new_list_node(NULL,0); | |
current = current->next; | |
} | |
} | |
return root; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment