Tests for singly linked list #devsample
/** | |
* Tests for singly linked list | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stddef.h> | |
#include <assert.h> | |
/* singly link list node */ | |
typedef struct _node | |
{ | |
int data; | |
struct _node *next; | |
} node; | |
/* return the middle node of the list. | |
* - The length of the list is odd: the middle node is list[(length + 1) /2] | |
* - The length of the list is even: the middle node is list[(length) /2] | |
*/ | |
static node* list_get_middle_node(node *hdr) | |
{ | |
node *slow_ptr = hdr; | |
node *fast_ptr = hdr; | |
if (NULL == hdr) | |
{ | |
return NULL; | |
} | |
for (; NULL != fast_ptr && NULL != fast_ptr->next;) | |
{ | |
fast_ptr = fast_ptr->next->next; | |
slow_ptr = slow_ptr->next; | |
} | |
return slow_ptr; | |
} | |
/* inserts a new element at the beginning of the list. */ | |
static node* list_push_front(node *hdr, int data) | |
{ | |
node *item = (node *)malloc(sizeof(node)); | |
assert(NULL != item); | |
item->data = data; | |
item->next = hdr; | |
return item; | |
} | |
/* free all node */ | |
static void list_free(node *hdr) | |
{ | |
node *item; | |
for (item = hdr; NULL != item; ) | |
{ | |
hdr = hdr->next; | |
free(item); | |
item = hdr; | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
node *root = NULL; | |
node *middle_node = NULL; | |
/* prepare test list */ | |
root = list_push_front(root, 1); | |
root = list_push_front(root, 2); | |
root = list_push_front(root, 3); | |
root = list_push_front(root, 4); | |
root = list_push_front(root, 5); | |
root = list_push_front(root, 6); | |
root = list_push_front(root, 7); | |
/* get and print the middle node */ | |
middle_node = list_get_middle_node(root); | |
printf("Middle node %d\n", NULL == middle_node ? -1 : middle_node->data); | |
/* free the list */ | |
list_free(root); | |
root = NULL; | |
return 0; | |
} |
# CMake build script (read .ini) | |
cmake_minimum_required(VERSION 2.8) | |
# project name & version | |
project(LinkedList) | |
include_directories("${PROJECT_SOURCE_DIR}") | |
# application | |
add_executable(linkedlist-test | |
"${PROJECT_SOURCE_DIR}/0-main.c") | |
# install | |
install(TARGETS linkedlist-test DESTINATION bin) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment