1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -

Slides:



Advertisements
Similar presentations
Queues CS 308 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: –Elements are added at.
Advertisements

What is a Queue? n Logical (or ADT) level: A queue is an ordered group of homogeneous items (elements), in which new elements are added at one end (the.
Queues CS 3358 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: – Elements are added.
What is a Queue? A queue is a FIFO “first in, first out” structure.
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Chapter 5 ADTs Stack and Queue. 2 Goals Describe a stack and its operations at a logical level Demonstrate the effect of stack operations using a particular.
1 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Informática II Prof. Dr. Gustavo Patiño MJ
Doubly-Linked Lists Same basic functions operate on list Each node has a forward and backward link: What advantages does a doubly-linked list offer? 88.
CS Data Structures Chapter 8 Lists Mehmet H Gunes
Chapter 4 ADT Sorted List.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
1 C++ Plus Data Structures Nell Dale Queues ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Stacks CS 308 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
5 Linked Structures. 2 Definition of Stack Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Fall Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Chapter 3 ADT Unsorted List. Lecture 7 List Definitions Linear relationship Each element except the first has a unique predecessor, and Each element.
Data Structures Lecture-12 : STL Azhar Maqsood NUST Institute of Information Technology (NIIT)
What is a Stack? n Logical (or ADT) level: A stack is an ordered group of homogeneous items in which the removal and addition of items can take place only.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and each element except the last has.
1 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Data Structures: Stacks Queues 1. 2 Stack ADT: What is a Stack? a stack is a varying-length, collection of homogeneous elements Insertion and Deletion.
Chapter 5 ADTs Stack and Queue. Stacks of Coins and Bills.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
1 Data Structures and Algorithms Stacks and Queues.
1 C++ Plus Data Structures Nell Dale Chapter 5 Linked Structures Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Chapter 4 ADT Sorted List. Sorted Type Class Interface Diagram SortedType class IsFull GetLength ResetList DeleteItem PutItem MakeEmpty GetItem Private.
1 Chapter 4 ADT Sorted List. 2 Sorted Type Class Interface Diagram SortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CSI 1340 Introduction to Computer Science II Chapter 6 Lists Plus.
Chapter 5 (Part 1) ADT Stack 1 Fall Stacks TOP OF THE STACK.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
1 C++ Plus Data Structures Abstract Data Types Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 18: Stacks and Queues.
Chapter 14 Dynamic Data and Linked Lists
Chapter 18: Stacks and Queues.
C++ Plus Data Structures
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Chapter 5 ADTs Stack and Queue.
Chapter 16-2 Linked Structures
Chapter 19: Stacks and Queues.
C++ Plus Data Structures
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 5 ADTs Stack and Queue Fall 2013 Yanjun Li CS2200.
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 16 Linked Structures
CSI 1340 Introduction to Computer Science II
C++ Plus Data Structures
CSI 1340 Introduction to Computer Science II
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

2 Stacks

3 Stacks of Coins and Bills

4 Stacks What is a stack? l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of stack items can take place only at the top of the stack. l A stack is a LIFO “last in, first out” structure.

5 Stacks of Boxes and Books TOP OF THE STACK

Stack ADT Operations l MakeEmpty -- Sets stack to an empty state. l IsEmpty -- Determines whether the stack is currently empty. l IsFull -- Determines whether the stack is currently full. l Push (ItemType newItem) -- Adds newItem to the top of the stack. l Pop (ItemType& item) -- Removes the item at the top of the stack and returns it in item. 6

ADT Stack Operations Transformers n MakeEmpty n Push n Pop Observers n IsEmpty n IsFull change state observe state 7

// // SPECIFICATION FILE (stack.h) // #include "bool.h" #include "ItemType.h" // for MAX_ITEMS and // class ItemType definition class StackType { public: StackType( ); // Default constructor. // POST: Stack is created and empty. void MakeEmpty( ); // PRE: None. // POST: Stack is empty. bool IsEmpty( ) const; // PRE: Stack has been initialized. // POST: Function value = (stack is empty) 8

// SPECIFICATION FILE continued (Stack.h) bool IsFull( ) const; // PRE: Stack has been initialized. // POST: Function value = (stack is full) void Push( ItemType newItem ); // PRE: Stack has been initialized and is not full. // POST: newItem is at the top of the stack. void Pop( ItemType& item ); // PRE: Stack has been initialized and is not empty. // POST: Top element has been removed from stack. // item is a copy of removed element. private: int top; ItemType items[MAX_ITEMS];// array of ItemType }; 9

10 Private data value Print Initialize class ItemType ItemType Class/Struct Interface Diagram

// // IMPLEMENTATION FILE (Stack.cpp) // // Private data members of class: //int top; //ItemType items[MAX_ITEMS]; // #include “bool.h” #include “ItemType.h” StackType::StackType( ) // // Default Constructor // { top = -1; } 11

// IMPLEMENTATION FILE continued (Stack.cpp) // void StackType::MakeEmpty( ) // // PRE: None. // POST: Stack is empty. // { top = -1; } 12

// IMPLEMENTATION FILE continued (Stack.cpp) // bool StackType::IsEmpty( ) const // // PRE: Stack has been initialized. // POST: Function value = (stack is empty) // { return ( top == -1 ); } bool StackType::IsFull( ) const // // PRE: Stack has been initialized. // POST: Function value = (stack is full) // { return ( top == MAX_ITEMS-1 ); } 13

// IMPLEMENTATION FILE continued (Stack.cpp) // void StackType::Push ( ItemType newItem ) // // PRE: Stack has been initialized and is not full. // POST: newItem is at the top of the stack. // { top++; items[top] = newItem; } 14

// IMPLEMENTATION FILE continued (Stack.cpp) // void StackType::Pop ( ItemType& item ) // // PRE: Stack has been initialized and is not empty. // POST: Top element has been removed from stack. // item is a copy of removed element. // { item = items[top]; top--; } 15

16 Class Interface Diagram StackType class StackType MakeEmpty Pop Push IsFull IsEmpty Private data: top [MAX_ITEMS-1]. [ 2 ] [ 1 ] items [ 0 ]

17 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code Private data: top [ MAX_ITEMS-1 ]. [ 2 ] [ 1 ] items [ 0 ] letter ‘V’

18 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘V’ Private data: top -1 [ MAX_ITEMS-1 ]. [ 2 ] [ 1 ] items [ 0 ]

19 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘V’ Private data: top 0 [ MAX_ITEMS-1 ]. [ 2 ] [ 1 ] items [ 0 ] ‘V’

20 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘V’ Private data: top 1 [ MAX_ITEMS-1 ]. [ 2 ] [ 1 ] ‘C’ items [ 0 ] ‘V’

21 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘V’ Private data: top 2 [ MAX_ITEMS-1 ]. [ 2 ] ‘S’ [ 1 ] ‘C’ items [ 0 ] ‘V’

22 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘V’ Private data: top 2 [ MAX_ITEMS-1 ]. [ 2 ] ‘S’ [ 1 ] ‘C’ items [ 0 ] ‘V’

23 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘S’ Private data: top 1 [ MAX_ITEMS-1 ]. [ 2 ] ‘S’ [ 1 ] ‘C’ items [ 0 ] ‘V’

24 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘S’ Private data: top 2 [ MAX_ITEMS-1 ]. [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

25 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘S’ Private data: top 2 [ MAX_ITEMS-1 ]. [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

26 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘K’ Private data: top 1 [ MAX_ITEMS-1 ]. [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

27 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘K’ Private data: top 1 [ MAX_ITEMS-1 ]. [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

28 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘C’ Private data: top 0 [ MAX_ITEMS-1 ]. [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

29 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘C’ Private data: top 0 [ MAX_ITEMS-1 ]. [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

30 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); Tracing Client Code letter ‘V’ Private data: top -1 [ MAX_ITEMS-1 ]. [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

31 charletter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop(letter); charStack.Push(‘K’); while (!charStack.IsEmpty( )) charStack.Pop(letter); End of Trace letter ‘V’ Private data: top -1 [ MAX_ITEMS-1 ]. [ 2 ] ‘K’ [ 1 ] ‘C’ items [ 0 ] ‘V’

32 What is a Class Template? l A class template allows the compiler to generate multiple versions of a class type by using type parameters. l The formal parameter appears in the class template definition, and the actual parameter appears in the client code. Both are enclosed in pointed brackets,.

// Laboratory 4, Class declaration... listarr.h... template class List { public: List ( int maxNumber = defMaxListSize ); ~List (); void insert ( const LE &newElement ); void remove ();... LE getCursor () const; // Return element.. void moveToNth ( int n ); // InLab 2 int find ( const LE &searchElement ); // InLab 3 private: // Data members int maxSize, size, cursor; LE *element; // Array containing the list elements }; 33

// Laboratory 4, Class implementation... listarr.cpp #include #include "listarr.h" // template List :: List ( int maxNumber ) // Creates an empty list. Allocates enough memory for maxNumber // elements (defaults to defMaxListSize). : maxSize(maxNumber),size(0),cursor(-1) { element = new LE [ maxSize ]; assert ( element != 0 ); } // template List :: ~List () // Frees the memory used by a list. { delete [] element; } //

//Laboratory 4, Client code: test4.cpp (modified) #include #include "listarr.cpp" void main() { List testList_char(8); // Test list List testList_int(10); // Test list char testElement_char; // List element int testElement_int; // List element... } 35

List testList_char(8); [ 7 ]. [ 3 ] B [ 2 ] A [ 1 ] R element [ 0 ] M 36 ACTUAL PARAMETER

List testList_int(10); [ 9 ]. [ 3 ] 789 [ 2 ] -56 [ 1 ] 132 element [ 0 ] ACTUAL PARAMETER

Using class templates l The actual parameter to the template is a data type. Any type can be used, either built-in or user-defined. 38

39 Pointer Types Recall that … char msg [ 8 ]; msg is the base address of the array. We say msg is a pointer because its value is an address. It is a pointer constant because the value of msg itself cannot be changed by assignment. It “points” to the memory location of a char. msg [0] [1] [2] [3] [4] [5] [6] [7] ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ 6000

40 Addresses in Memory l When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is the address of the variable. int x; float number; char ch; x number ch

41 Obtaining Memory Addresses l The address of a non-array variable can be obtained by using the address-of operator &. int x; float number; char ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number << endl; cout << “Address of ch is “ << &ch << endl;

42 What is a pointer variable? l A pointer variable is a variable whose value is the address of a location in memory. l To declare a pointer variable, you must specify the type of value that the pointer will point to. For example, int* ptr; // ptr will hold the address of an int char* q; // q will hold the address of a char

43 Using a pointer variable int x; x = 12; int* ptr; ptr = &x; NOTE: Because ptr holds the address of x, we say that ptr “points to” x x ptr

x ptr int x; x = 12; int* ptr; ptr = &x; cout << *ptr; NOTE: The value pointed to by ptr is denoted by *ptr Unary operator * is the deference (indirection) operator

45 int x; x = 12; int* ptr; ptr = &x; *ptr = 5; // changes the value // at adddress ptr to 5 Using the dereference operator x ptr

46 char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; // the right side has value 4000 // now p and q both point to ch Another Example 4000 A Z ch q p

47 C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double

48 The NULL Pointer There is a pointer constant 0 called the “null pointer” denoted by NULL in stddef.h But NULL is not memory address 0. NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this. while (ptr != NULL) {... // ok to use *ptr here }

49 Allocation of memory STATIC ALLOCATION Static allocation is the allocation of memory space at compile time. DYNAMIC ALLOCATION Dynamic allocation is the allocation of memory space at run time by using operator new.

50 3 Kinds of Program Data l STATIC DATA: memory allocation exists throughout execution of program. static long SeedValue; l AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function. DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using unary operators new and delete

Using operator new If memory is available in an area called the free store (or heap), operator new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated. Otherwise, the null pointer 0 is returned. The dynamically allocated object exists until the delete operator destroys it. 51

ptr Dynamically Allocated Data char* ptr = 0; ptr = new char; *ptr = ‘B’; cout << *ptr;

53 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr

54 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr ‘B’

55 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; 2000 ptr NOTE: Delete deallocates the memory pointed to by ptr. ?

The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned. The memory is returned to the free store. Square brackets are used with delete to deallocate a dynamically allocated array of classes. Using operator delete 56

Some C++ pointer operations Precedence Higher -> Select member of class pointed to Unary: ! * new delete Increment, Decrement, NOT, Dereference, Allocate, Deallocate + - Add Subtract >= Relational operators == != Tests for equality, inequality Lower = Assignment

58 Dynamic Array Allocation char *ptr; // ptr is a pointer variable that // can hold the address of a char ptr = new char[ 5 ]; // dynamically, during run time, allocates // memory for 5 characters and places into // the contents of ptr their beginning address ptr 6000

59 Dynamic Array Allocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; // a pointer can be subscripted cout << ptr[ 2] ; ptr 6000 ‘B’ ‘y’ ‘e’ ‘\0’ ‘u’

60 Dynamic Array Deallocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; delete [ ] ptr; // deallocates array pointed to by ptr // ptr itself is not deallocated, but // the value of ptr is considered unassigned ptr ?

61 int* ptr = new int; *ptr = 3; ptr = new int; // changes value of ptr *ptr = 4; What happens here? 3 ptr 3 ptr 4

62 Memory Leak A memory leak occurs when dynamic memory (that was created using operator new ) has been left without a pointer to it by the programmer, and so is inaccessible. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; How else can an object become inaccessible? 8 ptr -5 ptr2

63 Causing a Memory Leak int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; // here the 8 becomes inaccessible 8 ptr -5 ptr2 8 ptr -5 ptr2

64 occurs when two pointers point to the same object and delete is applied to one of them. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; A Dangling Pointer 8 ptr -5 ptr2 FOR EXAMPLE,

65 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr2 = NULL; Leaving a Dangling Pointer 8 ptr -5 ptr2 8 ptr NULL ptr2

66 Queues What is a queue? l Logical (or ADT) level: A queue is an ordered group of homogeneous items (elements), in which new elements are added at one end (the rear), and elements are removed from the other end (the front). l A queue is a FIFO “first in, first out” structure.

Queue ADT Operations l MakeEmpty -- Sets queue to an empty state. l IsEmpty -- Determines whether the queue is currently empty. l IsFull -- Determines whether the queue is currently full. l Enqueue (ItemType newItem) -- Adds newItem to the rear of the queue. l Dequeue (ItemType& item) -- Removes the item at the front of the queue and returns it in item. 67

ADT Queue Operations Transformers n MakeEmpty n Enqueue n Dequeue Observers n IsEmpty n IsFull change state observe state 68

Queue Designs 69

Queue Designs Queue can be stored in a l Static array – with its size fixed at compile time or l Dynamically allocated array – with its size determined at run time. 70

71 DYNAMIC ARRAY IMPLEMENTATION QueType ~QueType Enqueue Dequeue. class QueType Private Data: front 1 rear 4 maxQue 5 items ‘C’ ‘X’ ‘J’ items [0] [1] [2] [3] [4] RESERVED

// // CLASS TEMPLATE DEFINITION FOR CIRCULAR QUEUE (queue.h) #include "ItemType.h" // for ItemType template class QueType { public: QueType( ); QueType( int max );// PARAMETERIZED CONSTRUCTOR ~QueType( ) ;// DESTRUCTOR... bool IsFull( ) const; void Enqueue( ItemType item ); void Dequeue( ItemType& item ); private: int front; int rear; int maxQue; ItemType* items; // DYNAMIC ARRAY IMPLEMENTATION }; 72

// // SPECIFICATION FILE (stack.h) // #include "bool.h" #include "ItemType.h" // for MAX_ITEMS and // class ItemType definition class StackType { public: … private: int top; ItemType items[MAX_ITEMS];//STATIC ARRAY IMPLEMENTATION }; 73 Compare to …

// // CLASS TEMPLATE DEFINITION FOR CIRCULAR QUEUE cont’d // template QueType ::QueType( int max ) // PARAMETERIZED { maxQue = max + 1; front = maxQue - 1; rear = maxQue - 1; items = new ItemType[maxQue]; // dynamically allocates } template bool QueType ::IsEmpty( ) { return ( rear == front ) } 74

// // CLASS TEMPLATE DEFINITION FOR CIRCULAR QUEUE cont’d // template QueType ::~QueType( ) { delete [ ] items; // deallocates array }. template bool QueType ::IsFull( ) {// WRAP AROUND return ( (rear + 1) % maxQue == front ) } 75

End 76