Reputation: 113
I'm working on a school project and I'm trying to understand doubly linked lists and structs a bit better. Currently, I'm trying to implement a function, one that creates a new linked list. Because I think I can work from there.
typedef struct ListItem {
struct ListItem *previousItem; //pointer to previous item, NULL if first list item
struct ListItem *nextItem; //pointer to next item, NULL if first list item
void *data; //pointer to data
This is the struct for the doubly linked list I am trying to make. I know that a "void *" can hold a pointer to anything, also that I have to allocate any data stored in the list item.
/**
* This function starts a new linked list. Given an allocated pointer to data it will return a
* pointer for a malloc()ed ListItem struct. If malloc() fails for any reason, then this function
* returns NULL otherwise it should return a pointer to this new list item. data can be NULL.
*
* @param data The data to be stored in the first ListItem in this new list. Can be any valid
* pointer value.
* @return A pointer to the malloc()'d ListItem. May be NULL if an error occured.
*/
ListItem *NewList(void *data);
I know that malloc() allocates enough memory on the stack for use, so I think that in my function I have to malloc() *previousItem, *nextItem, and *data (which would be 6 bytes?) Other than that, to implement the function all I would do is copy the ListItem struct? The previous AND next item would be NULL pointers since it is the only item in the list, and the *data would be the input I think. Can anyone give me an idea of what my code would look like?
Upvotes: 0
Views: 401
Reputation: 120714
You're on the right track. Instead of using 6
as the argument to malloc
, you could use sizeof
to get the amount of memory that you need to allocate - for example:
ListItem *node = malloc(sizeof(ListItem));
After that the implementation is fairly trivial:
/* Make sure that allocation succeeded */
...
/* Assign the right values to previousItem and nextItem */
...
/* Assign the right value to data */
...
/* Return the pointer to the new list */
...
Someone else will probably submit the full function, but your english language description of what needs to happen is spot on (other than the whole heap vs. stack thing).
Upvotes: 2