Presentation is loading. Please wait.

Presentation is loading. Please wait.

Linked Lists Chris Wright Winter 2006.

Similar presentations


Presentation on theme: "Linked Lists Chris Wright Winter 2006."— Presentation transcript:

1 Linked Lists Chris Wright Winter 2006

2 Malloc void* malloc(size_t size); sizeof
Returns a pointer to a block of memory of size size. If there is not enough memory it will return NULL. sizeof Gives the size_t of an item Works perfectly with malloc Data* dataptr = (Data*)malloc(sizeof(Data));

3 Free The counterpart to malloc Frees the memory set aside by malloc
Must be used anytime you are done with a malloc’d block of memory. Data* dataptr = (Data*)malloc(sizeof(Data)); // Code using dataptr free(dataptr); dataptr = (Data*)malloc(sizeof(Data));

4 Linked List

5 Linked List add_end

6 Linked List delete_node

7 List.h (1) struct node_struct { int data; struct node_struct* next;
struct node_struct* prev; }; typedef struct node_struct node; struct list_struct node* head; node* tail; typedef struct list_struct list;

8 List.h (2) list* create_list(); void delete_list(list* listptr);
void add_end(list* listptr, int data); void delete_node(list* listptr, node* nodeptr);

9 List.c (1) list* create_list(){
list* listptr = (list *)malloc(sizeof(list)); listptr->head = NULL; listptr->tail = NULL; return listptr; } void delete_list(list* listptr){ while(listptr->head != NULL){ remove(listptr, listptr->head); free(listptr);

10 List.c (2) void add_end(list* listptr, int data) {
node* last_node = listptr->tail; node* new_node = (node *)malloc(sizeof(node)); new_node->data = data; new_node->prev = last_node; new_node->next = NULL; if(last_node != NULL) last_node->next = new_node; listptr->tail = new_node; if(listptr->head == NULL) listptr->head = new_node; }

11 List.c (3) void delete_node(list* listptr, node* nodeptr) {
node* prev_node = nodeptr->prev; node* next_node = nodeptr->next; if(prev_node == NULL) listptr->head = next_node; else prev_node->next = next_node; if(next_node == NULL) listptr->tail = prev_node; next_node->prev = prev_node; free(nodeptr); }


Download ppt "Linked Lists Chris Wright Winter 2006."

Similar presentations


Ads by Google