Download presentation
Presentation is loading. Please wait.
Published byColeman Peck Modified over 10 years ago
1
Linked Lists CSE 2451 Matt Boggus
2
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
3
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?
4
Dynamic arrays – realloc See remember.c example
5
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
6
Singly linked list node /* Node Structure */ struct node { int data; struct node *next; }
7
Doubly linked list node /* Node Structure */ struct node { int data; struct node *next; struct node *prev; }
8
NULL terminated lists Singly linked Doubly linked Boxes with x represent NULL values
9
Circularly linked lists Last pointer is set to the first node
10
Accessing lists Still need a pointer to that refers to the first node in the list: head pointer struct node * head
11
Adding nodes Step through the list until the correct location is found (for a sorted list) newNodes pointer = nodes pointer nodes pointer = newNode
12
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
13
Removing nodes Step through the list until the node is found nodes pointer = node.nexts pointer Need a pointer to node.next for free
14
Lab3
15
Additional examples http://rosettacode.org/wiki/Linked_list http://www.macs.hw.ac.uk/~rjp/Coursewww/ Cwww/linklist.html http://www.macs.hw.ac.uk/~rjp/Coursewww/ Cwww/linklist.html – Building a linked list, but not freeing it
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.