You are on page 1of 69

Lecture 2 - Pointers

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)

• A pointer is a variable whose value is the address of another variable in


memory

• Given the declarations


int i=15,j,*p,*q;
i and j are integer variables, while p and q are pointers to integer
variables

2
Pointers : Dynamic memory allocation
• Creating memory during runtime using the memory manager

• Two functions are used to handle dynamic memory


– To allocate memory, new is used; it returns the address of the allocated
memory, which can be assigned to a pointer
p = new int;
– To release the memory pointed at, delete is used
delete p;

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

• Now remember that a pointer can be used in the allocation of


memory without a name, through the use of new
• This means that we can also declare an array dynamically, via
int *p; p = new int[n];
• As long as the value of n is known when the declaration is executed,
the array can be of arbitrary size

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,

• Each time we encounter a closing


symbol, we pop the top symbol from
the stack S and we check that these
two symbols are of corresponding
types.

• If the stack is empty after we have


processed the whole sequence, then
the symbols in X match.
Lecture 10 – Queues
Queue
• Queue is a fundamental data structure
• A queue is a container of elements that are inserted and removed
according to the first-in first-out (FIFO) principle.
• We usually say that elements enter the queue at the rear and are
removed from the front.
Queue ADT illustration
Example of the implementation so far
• Lets say we have the following:
• N = 5 and an array of integers called Q which we will use as a queue
• Draw your queue and keep track of f,r,n as we execute the
following: Operation f r n

• 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

© 2010 Goodrich, Tamassia Lists 38


Applications of Sequences
• The Sequence ADT is a basic, general-purpose,
data structure for storing an ordered collection of
elements
• Direct applications:
• Generic replacement for stack, queue, vector, or list
• small database (e.g., address book)
• Indirect applications:
• Building block of more complex data structures

© 2010 Goodrich, Tamassia Iterators and Sequences 39


Bubble Sort Algorithm
• The bubble-sort algorithm has the following properties:
•In the first pass, once the largest element is reached, it keeps on being
swapped until it gets to the last position of the sequence.
• In the second pass, once the second largest element is reached, it keeps on
being swapped until it gets to the second-to-last position of the sequence.
And So on…
Bubble Sort Algorithm
Lecture 14 – General Trees
A

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

• External node (a.k.a. leaf ):


node without children (E, I, J, K, G, H, D) I J K
• Ancestors of a node: parent, grandparent, grand-grandparent, etc.
• Depth of a node: number of ancestors
• Height of a tree: maximum depth of any node (3)
• Descendant of a node: child, grandchild, grand-grandchild, etc.
• Subtree: A tree within a bigger tree
• Siblings: Two nodes that are children of the same parent are siblings
• An edge of tree T is a pair of nodes (u,v) such that u is the parent of v, or vice versa.
• A path of T is a sequence of nodes such that any two consecutive nodes in the sequence form an edge.
Tree Traversal
• A traversal visits the nodes of a tree in a systematic manner
• Three types of traversals
• Pre order
• Post order
• In order

• Before we learn about traversal, lets look at some terminologies


again
• Depth: Let p be a node of a tree T. The depth of p is the number of ancestors
of p, excluding p itself.
• Height: The height of a node p in a tree T is also defined recursively.
• If p is external, then the height of p is 0
• Otherwise, the height of p is one plus the maximum height of a child of p
Preorder Traversal
Algorithm preOrder(v)
visit(v)
for each child w of v
preorder (w)

In a preorder traversal of a tree T, the root of T


is visited first and then the subtrees rooted at its
children are traversed recursively.
Post order traversal
• In postorder traversal, we visit a node p after we have visited all the
other nodes in the subtree rooted at p.
Lectures 17 and 18 – Binary Tree
Binary Tree Definition
• A binary tree is an ordered tree data structure with the following properties:
• Each internal node has at most two children (exactly two for proper binary trees)
• Each child is labeled as being a left child or a right child
• A left child comes before a right child in the ordering of the children of any node
• Recursive definition: a binary tree is either
• a tree consisting of a single node, or A
• a tree whose root has an ordered pair of children, each of which is a binary tree
 Example Applications:
B C
 arithmetic expressions
 decision trees
 searching
D E F G

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

• A heap is a binary tree storing keys • The last node of a heap is


at its nodes and satisfying the the rightmost node of
following properties: maximum depth
• We can use a heap to implement a
priority queue
• We store a (key, element) item at each
2
internal node
5 6
• We keep track of the position of the last
node
9 7

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

//mistake: should be P5 instead of P4


Lecture 27 - Graph
Graphs
• A graph is a way of representing relationships that exist between pairs of objects.
• It is a pair (V, E), where
• V is a set of nodes, called vertices
• E is a collection of pairs of vertices, called edges
• Vertices and edges are positions and store elements
• Example:
• A vertex represents an airport and stores the three-letter airport code
• An edge represents a flight route between two airports and stores the mileage of the route

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

You might also like