170 likes | 270 Views
Linked Lists. CSE 2451 Matt Boggus. Dynamic memory reminder. Allocate memory during run-time malloc () and calloc () – return a void pointer to memory or a NULL pointer if allocation failed The programmer must check for the NULL value before dereferencing the pointer
E N D
Linked Lists CSE 2451 Matt Boggus
Dynamic memory reminder • Allocate memory during run-time • malloc() and calloc() – return a void pointer to memory or a NULL pointer if allocation failed • The programmer must check for the NULL value before dereferencing the pointer • free() – relinquishes memory allocated during run-time • Every malloc and calloc call should have a corresponding free call later • Pointer value is not changed after free, but it is not safe to dereference it (dangling pointer) • Memory leak • Memory that has been • Dynamically allocated, • Not freed, and • Is no longer in use/there is no pointer to it
Dynamic memory example/practice int x; int*pi; pi = (int*)malloc(5 * sizeof(int)); if (pi == NULL) { printf(“Out of memory!\n”); exit(1); } for (x = 0; x < 5; x +=1) *pi++ = 1; // Print array // free memory • What are the values in the new memory before initializing to zero? • Where is pi pointing to after the for loop? • How to free?
Dynamic arrays – realloc See remember.c example
Linked list • Data structure consisting of a group of nodes which together represent a sequence • A node consists of • Data • A reference/link/pointer to the next node in the sequence • Advantages • Efficient insertion or removal of elements from any position • Data items do not have to be stored contiguously in memory • Disadvantage • No random access or efficient indexing
Singly linked list node /* Node Structure */ struct node { intdata; structnode *next; }
Doubly linked list node /* Node Structure */ struct node { intdata; structnode *next; struct node *prev; }
NULL terminated lists • Singly linked • Doubly linked Boxes with x represent NULL values
Circularly linked lists • Last pointer is set to the first node
Accessing lists • Still need a pointer to that refers to the first node in the list: head pointer structnode * head
Adding nodes • Step through the list until the correct location is found (for a sorted list) • newNode’s pointer = node’s pointer • node’s pointer = newNode
List search found = false; ptr = head; while(ptr != NULL) { if(ptr->data = = val) { found = true; break; } else { ptr= ptr->next; } } // found = true then ptr points to that node // found = false then value is not in the list, ptr is NULL
Removing nodes • Step through the list until the node is found • node’s pointer = node.next’s pointer • Need a pointer to node.next for free
Additional examples • http://rosettacode.org/wiki/Linked_list • http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html • Building a linked list, but not freeing it