CMPSC 311, Linked Lists in C
Reading
- C:ARM, Sec. 5.3, Pointer Types. (review)
- C:ARM, Sec. 5.6, Structure Types.
/* CMPSC 311, Linked List, demo version 1a
* data structures
* function prototypes
* functions
* test program
*/
struct node {
};
struct list {
};
struct list demo;
list_insert(demo, node_create(“foo”));
list_print(demo);
// What’s wrong here?
[discussion]
/* CMPSC 311, Linked List, demo version 1b
* data structures
* function prototypes
* functions
* test program
*
* The
symbol *** represents code omitted for now,
* to be supplied later.
*/
// data structures
struct node {
};
struct list {
};
// function prototypes
struct node *node_create(char *name);
struct list *list_create(char *name);
void list_insert(struct list *list, struct node *node);
void list_print(struct list *list);
// functions
// test program
// statically-allocated
list header (global)
struct list demo1 =
***;
int main(int argc, char *argv[])
{
// automatically-allocated
list header (local)
struct list
demo2 = ***;
for (int i = 0; i < argc; i++)
{
list_insert(&demo2,
node_create(argv[i]));
}
list_print(&demo2);
// dynamically-allocated
list header (local pointer)
struct list
*demo3 = list_create("demo3");
for (int i = 0; i < argc; i++)
{
list_insert(demo3, node_create(argv[i]));
}
list_print(demo3);
return 0;
}
// Draw a map of the memory, and
indicate where the lists and nodes are.
// What’s wrong here? [discussion]
/* CMPSC 311, Linked List, demo version 1c
*/
// data structures
struct node {
struct node *next;
char *name;
void *data;
};
struct list {
struct node *head;
char *name;
};
// This requires C99.
#define NODE_INIT { .next = NULL, .name = "", .data = NULL
}
#define NODE_EMPTY (struct
node) NODE_INIT
#define LIST_INIT { .head = NULL, .name = "" }
#define LIST_EMPTY (struct list) LIST_INIT
// example
struct list demo = LIST_INIT;
demo = LIST_EMPTY;
// function prototypes
struct node *node_create(char *name);
struct node *list_create(char *name);
// functions
struct node *node_create(char *name)
{
struct node *ptr = malloc(sizeof(struct node));
ptr->next = NULL;
ptr->name = name;
ptr->data = NULL;
return ptr;
}
struct list *list_create(char
*name)
{
struct list *ptr =
malloc(sizeof(struct list));
ptr->head = NULL;
ptr->name = name;
return ptr;
}
// What’s wrong here? [discussion]
/* CMPSC 311, Linked List, demo version 1d
*/
// function prototypes
void list_init(struct list *list, char *name);
void list_make_empty(struct list *list);
// functions
void list_init(struct list *list, char *name)
{
list_make_empty(list);
list->name = name;
}
void list_make_empty(struct list *list)
{
***
}
Some different designs
Last revised, 28 July 2008