Cpts 122: Instructor - Nadra Guizani Cpts 122 (January 17, 2020) Washington State University
Cpts 122: Instructor - Nadra Guizani Cpts 122 (January 17, 2020) Washington State University
• But so far everything has been static. Once a size of the data
structure has been defined that is all we can modify.
Data Structures 2.0
• In this course we will focus on dynamic data structures
• Data structures will be able to grow and shrink at run-time
• Implementing in both C/C++
• Lists
• Stacks
• Queues
• Binary Trees and Binary Search Trees (BSTs)
Lists
• Collection of data items
that are lined up in a row
like format
• Insertion and deletion can
happen anywhere
• Examples:
• Grocery store list
• Music/Movie Collection
• Etc.
Stacks
• Restricted lists
• Insertions and deletions
may be made at one end
only
• These are Last In, First
Out (LIFO) structures
Queues
• Also a restricted list
• Insertions are made at the
back of the queue and
deletions are made from the
front
• These are First In, First Out
(FIFO) structures
• Examples: Waiting in line for
a ticket, appointment, or
grocery
BSTs
• require linked data items
• Efficient for searching and sorting
of data
• May represent directories on a file
system, etc.
Implementation of Dynamic Structures
• Implementing in both C and C++
• All will have growing and shrinking properties
• Implemented heavily dependent through both
• Pointers
• Structs – –self-referential structures for linked implementations
Self-Referential Structure
• struct which contains a pointer field that represents an address of a struct of
the same type
• Example:
Dynamic Allocation in C
• The growing and shrinking properties may be achieved through functions
located in <stdlib.h> including:
- malloc() for allocating/growing memory
- free() for de-allocating/shrinking memory
- realloc()for resizing memory
- Also consider calloc()
malloc()
malloc()
• Assume the following:
Node *pItem = NULL;
• How to use malloc()
pItem = (Node *) malloc (sizeof (Node));
// Recall malloc ( ) returns a void *,
// which should be typecasted
free()
• free (pItem);
// Requires the pointer to the memory to be
// de-allocated
realloc()
• pItem = realloc (pItem, sizeof (Node) * 2);
// Allocates space for two Nodes and
// returns pointer to beginning of resized //
memory
Book Reference
• C++: How to Program (10th ed.) HK 13.1 – 13.3,
• C: How to Program (8th ed.) DD C 12.1 – 12.3