91_pdfsam_cs2022 - Linked lists in C Function to add a cell...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Linked lists in C Function to add a cell to the head of the list returns a pointer to the new head of the list Function to print the contents of a list ListCell *add_front(ListCell *head, int data) { return make_ListCell(data, head); } void print_list(ListCell *head) { for( ; head ; head = head->next) printf(“%d\n”, head->data); }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Linked lists in C Function to destroy a ListCell like a destructor for ListCell in C++ Function to destroy an entire list void destroy_ListCell(ListCell *cell) { free(cell); } void destroy_list(ListCell *head) { ListCell *next; for( ; head ; head = next) { next = head->next; destroy_ListCell(head); } }
Background image of page 2
Linked lists in C int main() { ListCell *head = NULL; // list initially empty // Add 1, 2, 3, . .. 10 to the list for(int j=0; j<10; j++) head = add_front(head, j); // Print the first element of the list printf(“%d\n”, head->data); // Print the fourth element of the list printf(“%d\n”, head->next->next->next->data); // Print the contents of the list print_list(head); // Free memory allocated to list destroy_list(head); return 0; }
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

91_pdfsam_cs2022 - Linked lists in C Function to add a cell...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online