Professional Documents
Culture Documents
Pointers
• A variable defined in a program has two important attributes
• Its content or value (what it stores)
• Its location or address (where it is)
2
Pointers : Dynamic memory allocation
• Creating memory during runtime using the memory manager
3
Pointers and Arrays
• Typically, arrays in C++ are declared before they can be used, known
as static declaration
• Size of the array must be determined before it is used
4
Pointers and Destructors
• When a local object goes out of scope, the memory associated with it
is released
• Unfortunately, if one of the object members is a pointer, the pointer’s
memory is released, leaving the object pointed at inaccessible
• To avoid this memory leak, objects that contain pointers need to have
destructors written for them
• A destructor is a code construct that is automatically called when its
associated object is deleted
• It can specify special processing to occur, such as the deletion of
pointer-linked memory objects
5
Lecture 3 - Arrays
Using Arrays
• Built in arrays are used for all data types
• So far the easy examples have been the following
int a[10];
double *dob = new double[n];
char ch[]= {‘c’, ‘a’, ‘t’};
Example use of the array entries
Lecture 4 – Templates and Exceptions
Templates
• C++ provides polymorphism through inheritance
• We already know that
• Templates is another way that C++ provides polymorphism
• i.e., a single class or function can take several forms
• Both Functions and Classes can be designed as templates
Note the keywords
• The keyword typename keyword is new to C++, older versions used
the keyword class instead of typename.
Exceptions
• Exceptions are unexpected events that occur while the program is
running
• Can happen when the user puts in a bad input value
• Examples:
• Divide by zero in a calculator program
• Array index out of bounds (less than 0 or greater than or equal to max size)
• Negative number when calculating square roots
Generic Exception class: RuntimeException
• We will use this class as the Base class for all our exceptions in this
course.
• We can also use just this class and not bother designing anything else
Lecture 5 – Linked List
Singly Linked List
• Arrays are not adaptable: cant change size once it is allocated
• Vectors solve this problem by allowing expansion and reduction
• However, if used to insert and remove data
• Arrays and vectors need to be shifted left and right to keep the data sorted or
to fill the gap when something is removed
• Linked List is a collection of nodes that together form a linear
ordering
Singly Linked List
• In a singly linked list:
• Each node contains its internal data and a link or pointer to the next node of
the list
• Moving through the list using the next pointer is called link hopping/pointer
hopping
• First node in the list is called a head and they last is called a tail
• This structure is a singly linked list because each node stores only one link
• Linked lists can be maintained in an order and do not have a predetermined
size
Lecture 6 – Singly and Doubly Linked Lists
Inserting at the end of a singly linked list
• Since we did not keep a pointer to the tail
• We will have a hard time inserting in the end
• Step 1: Navigate the list to reach the last node
v = head;
while(v->next != NULL)
v = v->next
• Step 2: Create a new node
Node *n = new Node();
• Step 3: Attach the new node to the last node
v->next = n;
• Step 4: Make sure the new node points to NULL to indicate that it is the
new last node
n->next = NULL;
Doubly Linked List
• In a singly linked list:
It lakes long to remove any node other than the head
• In a doubly linked list, there are pointers going in both directions
• Each node stores two pointers, next and prev
• The header and trailer can be dummy nodes that provide quick access
to the lists head and tail nodes
Removing a node
Lecture 7 - Recursion
Recursion requirements
• Lets compare a loop and recursion
• What makes a loop exit? Stopping condition
• What makes a recursive procedure end? Base case
• Recursion is a way to use the solution of smaller problems to solve
progressively bigger problems
• Recursion is similar to mathematical induction
• You need mathematical induction to analyze the efficiency of a recursive
solution
Implementing Factorial function in C++
Illustration using Recursive Trace
• Each entry in the diagram corresponds to a recursive call
• Each new call is indicated by an arrow to the newly called function
• When a function ends, a curved arrow shows where it returns to.
Lecture 9 - Stacks
Example of stack operation
Matching parentheses and HTML tags
• Each time we encounter an opening
symbol, we push that symbol onto S,
• enqueue(5) enqueue(5) 0 1 1
enqueue(10) 0 2 2
• enqueue(10)
dequeue() 1 2 1
• dequeue()
enqueue(15) 1 3 2
• enqueue(15)
dequeue() 2 3 1
• dequeue()
dequeue() 3 3 0
enqueue(2) 3 4 1
dequeue() 4 4 0 NOW THE QUEUE
IS FULL!?
Lecture 11 - Vectors
Vector
• Vector is a sequential data structure that supports access to its
elements by its indices
• A vector is also called an array list
• Vector elements can be accessed just like an array
• Unlike arrays, the size of vectors can be increased dynamically
Example of vector operations
Lecture 12 – List and Iterators
Containers and Iterators
• An iterator abstracts the process of scanning through a collection of elements
• A container is an abstract data structure that supports element access through
iterators
• begin(): returns an iterator to the first element
• end(): return an iterator to an imaginary position just after the last element
• An iterator behaves like a pointer to an element
• *p: returns the element referenced by this iterator
• ++p: advances to the next element
• Extends the concept of position by adding a traversal capability
Lecture 13 – List, Sequence, Bubble Sort
Insertion
• We visualize operation insert(p, x), which inserts x before p
p
a b c
p
a b c
q
x
q p
a b x c
Tree Terminologies
• Root: node without parent (A) B C D
• Internal node:
node with at least one child (A, B, C, F)
E F G H
H I
Example Application: Arithmetic Expressions
• Binary tree associated with an arithmetic expression
• internal nodes: operators
• external nodes: operands
• Example: arithmetic expression tree for the expression (2 (a - 1) + (3 b))
2 - 3 b
a 1
Lecture 19 – Priority Queue and Comparator
Definition of a Priority Queue
• A priority queue is a container of elements, each associated with a
key, where the key determines the priority used to pick elements to
be removed.
• A priority queue stores a collection of entries
• Typically, an entry is a pair
(key, value), where the key indicates the priority
• Main methods of the Priority Queue ADT
• insert(e) - inserts an entry e
• removeMin() - removes the entry with smallest key
How to define the total order relationship
between elements in the priority queue?
• A) Template class for priority queue and overload relational operators
(<=, >=, ==) in each object type that we will store in the queue
• Such as overloading the operators in GameEntry
• B) By designing a separate objects called comparators that can let the
client code decide the total order relation among objects
Selection-Sort Example
Sequence S Priority Queue P
Input: (7,4,8,2,5,3,9) ()
Phase 1
(a) (4,8,2,5,3,9) (7)
(b) (8,2,5,3,9) (7,4)
.. .. ..
(g) () (7,4,8,2,5,3,9)
Phase 2
(a) (2) (7,4,8,5,3,9)
(b) (2,3) (7,4,8,5,9)
(c) (2,3,4) (7,8,5,9)
(d) (2,3,4,5) (7,8,9)
(e) (2,3,4,5,7) (8,9)
(f) (2,3,4,5,7,8) (9)
(g) (2,3,4,5,7,8,9) ()
© 2010 Goodrich, Tamassia Priority Queues 53
Insertion-Sort Example
Sequence S Priority queue P
Input: (7,4,8,2,5,3,9) ()
Phase 1
(a) (4,8,2,5,3,9) (7)
(b) (8,2,5,3,9) (4,7)
(c) (2,5,3,9) (4,7,8)
(d) (5,3,9) (2,4,7,8)
(e) (3,9) (2,4,5,7,8)
(f) (9) (2,3,4,5,7,8)
(g) () (2,3,4,5,7,8,9)
Phase 2
(a) (2) (3,4,5,7,8,9)
(b) (2,3) (4,5,7,8,9)
.. .. ..
(g) (2,3,4,5,7,8,9) ()
© 2010 Goodrich, Tamassia Priority Queues 54
Lectures 20 and 21 – Heap and Heap Sort
Heaps
last node
56
Lectures 22 and 23 – Map ADT and Hash
Tables
What is a MAP data structure
• A map models a searchable collection of key-value entries
• The main operations of a map are for searching, inserting, and
deleting entries
• Unique Keys: Multiple entries with the same key are not allowed
• Applications:
• address book
• student-record database
• Employee database
map Operations
Difference from Map?
• Hash tables allow multiple entries with the same key
• Collision
This will need to be a linked list or
a vector
Lecture 26 - Dictionary
What is a Dictionary data structure?
• Dictionary is like a map
• it stores key-value pairs (k,v), which we call entries, where k is the
key and v is the value.
• allows for keys and values to be of any object type.
• Dictionary is different from a map
• It allows for multiple entries to have the same key,
Example operations in a Dictionary ADT
PVD
ORD
SFO
LGA
HNL
LAX DFW
MIA
Edge Types
• Directed edge
• flight
•
ordered pair of vertices (u,v)
first vertex u is the origin
ORD AA 1206 PVD
• second vertex v is the destination
• e.g., a flight
• Undirected edge
849
• unordered pair of vertices (u,v) ORD PVD
• e.g., a flight route miles
• Directed graph (Digraph)
• all the edges are directed
• e.g., route network
• Undirected graph
• all the edges are undirected
• e.g., flight network
Terminology
• End vertices (or endpoints) of an edge
• U and V are the endpoints of a
• Edges incident on a vertex V
• a, d, and b are incident on V
a b
h j
• Adjacent vertices
U d X Z
• U and V are adjacent
• Degree of a vertex c e i
• X has degree 5 W g
• Parallel edges
• h and i are parallel edges f
• Self-loop
Y
• j is a self-loop
Paths
V
• Path a b
• sequence of alternating vertices and edges P1
• d
begins with a vertex U X Z
• ends with a vertex P2 h
• each edge is preceded and followed by its endpoints c e
• Simple path W g
• path such that all its vertices and edges are distinct
• Examples f
• P1=(V,b,X,h,Z) is a simple path Y
• P2=(U,c,W,e,X,g,Y,f,W,d,V) is a path that is not simple
Cycles
• Cycle
• circular sequence of alternating vertices and edges
V
a b
• each edge is preceded and followed by its endpoints
• Simple cycle d
U X Z
• cycle such that all its vertices and edges are distinct C2 h
e C1
• Examples c
• C1=(V,b,X,g,Y,f,W,c,U,a,) is a simple cycle W g
• C2=(U,c,W,e,X,g,Y,f,W,d,V,a,) is a cycle that is not simple
f
Y