Linked List
Here is a small exercise that helps you understand memory management and pointer operations in C.
Instructions
Implement a doubly linked list.
You will write an implementation of a doubly linked list with the following functions:
-
push
(insert value at back); -
pop
(remove value at back); -
shift
(remove value at front); -
unshift
(insert value at front); -
count
(count the number of nodes in the list); -
delete
(delete the node that holds the matched data); - etc.
To keep your implementation simple, the tests will not cover error
conditions. Specifically: pop
or shift
will never be called on an
empty list.
Tips
Since linked list is a dynamic data structure, you have to use memory management functions defined in <stdlib.h>
.
When you create a new node, you should allocate a block of memory for the node. When you delete a node or destroy the whole list, you should deallocate/free all previously allocated data.
Testing
The included makefile can be used to create and run the tests using the following commands:
# run unit tests
make test
# check memory leaks
make memcheck
# clean all compilation files
make clean
Credit
Adapted from here