Resource-Optimized Quality-Assured Ambiguous Context Mediation

Download Report

Transcript Resource-Optimized Quality-Assured Ambiguous Context Mediation

Cpt S 122 – Data Structures
Course Review
Midterm Exam # 1
Nirmalya Roy
School of Electrical Engineering and Computer Science
Washington State University
Midterm Exam 1


When: Friday (09/28) 12:10 -1pm
Where: In Class

Closed book, Closed notes
Comprehensive

Material for preparation:




Lecture Slides
Quizzes, Labs and Programming assignments
Deitel & Deitel book (Read and re-read Chapter 12)
Course Overview

Functions (Chapter 5)



Pointers (Chapter 7)




Function Call Stack and Stack Frames
Pass-by-value and Pass-by-reference
Pointer Operators
Passing Arguments to Functions by Reference
const qualifiers with Pointers
Characters and Strings (Chapter 8)

Fundamentals of Strings and Characters
Course Overview

Data Structures (Chapter 12)



Self Referential Structures
Dynamic Memory Allocation
Linked Lists, Stacks and Queues



Insert, delete, isEmpty, printList
Binary Trees, Binary Search Trees
Tree Traversals

inOrder, preOrder, postOrder
Functions Review (Chapter 5)

The data structure—working “behind the scenes”—
supports the function call/return mechanism.



Stack
Supports the creation, maintenance and destruction
of each called function’s automatic variables.
Stack overflow error

If more function calls occur since the amount of memory
is finite.
Functions Review (Chapter 5)

Two ways to pass arguments


passed by value




pass-by-value and pass-by-reference.
a copy of the argument’s value is made and passed to the called
function.
changes to the copy do not affect an original variable’s value in the
caller.
Pass-by-value is used whenever the called function does not need to
modify the value of the caller’s original variable.
passed by reference

the caller allows the called function to modify the original variable’s
value.
Pointers Review (Chapter 7)

Enables programs to simulate pass-by-reference.


pass functions between functions.
For creating and manipulating dynamic data structures
(i.e., data structures that can grow and shrink at
execution times).

Linked lists, queues, stacks, trees.
Pointer Variable Definitions and Initialization


Pointers are variables whose values are memory addresses.
Normally, a variable directly contains a specific value.


A variable directly references a value.
A pointer contains an address of a variable that contains a
specific value.


A pointer indirectly references a value.
Indirection means referencing a value through a pointer.
count
7
countPtr
count
Memory
Location of 7
7
count directly references
a variable that contains the value 7.
Pointer countPtr indirectly
references a variable that contains
the value 7.
Using the const Qualifier with Pointers


The const qualifier enables you to inform the
compiler that the value of a particular variable
should not be modified.
Four ways to pass a pointer to a function




Non-constant pointer to non-constant data
Non-constant pointer to constant data
Constant pointer to non-constant data
Constant pointer to constant data
Using the const Qualifier with Pointers

Non-constant pointer to non-constant data


The data can be modified through the dereferenced
pointer, and the pointer can be modified to point to
other data items.
Non-constant pointer to constant data

The non-constant pointer to constant data can be
modified to point to any data item of the appropriate
type, but the data to which it points cannot be modified.
Using the const Qualifier with Pointers

Constant pointer to non-constant data


A constant pointer to non-constant data always points to
the same memory location, and the data at that location
can be modified through the pointer.
Constant pointer to constant data

Such a pointer always points to the same memory
location, and the data at that memory location cannot
be modified.
Void, Null, Dangling Pointer

The void pointer, also known as the generic pointer, is
a special type of pointer that can be pointed at objects
of any data type.

A pointer to void cannot be dereferenced.

A null pointer has a value reserved for indicating that
the pointer does not refer to a valid object.

A dangling pointer is a pointer to storage that is no
longer allocated.
Characters and Strings (Chapter 8)

A char * needs to point to some allocated memory


A str[] has memory associated with it


str refers to the address of the 0th element in the array
A char *str[] is an array of pointers


this memory may be allocated dynamically or via another
automatic local variable
each pointer could refer to dynamically allocated memory or
automatic local variable memory
A str[][] may be considered an array of strings or a 2-D
array of characters

all required memory is allocated upfront; str[] (one index
specified) refers to the start of the corresponding row
Data Structures (Chapter 12)

Dynamic data structures with sizes that grow and shrink at
execution time

Linked lists are collections of data items “lined up in a row”


Stacks are important in compilers and operating systems


insertions and deletions are made only at one end of a stack—its top.
Queues represent waiting lines


insertions and deletions are made anywhere in a linked list.
insertions are made only at the back (also referred to as the tail) of a
queue and deletions are made only from the front (also referred to as the
head) of a queue.
Binary trees facilitate high-speed searching and sorting of data


efficient elimination of duplicate data items,
representing file system directories and compiling expressions into
machine language.
Abstract Data Type

Data abstraction and abstract data types (ADT).


notion of an object (from object-oriented programming) is an
attempt to combine abstractions of data and code.
ADT is a set of objects together with a set of operations



e.g., List, Operations on a list: Insert, delete, search, sort
C++ class are perfect for ADTs
Enable us to build the data structures in a dramatically
different manner designed for producing software that’s
much easier to maintain and reuse.
Self Referential Structures


A self-referential structure contains a pointer member
that points to a structure of the same structure type.
For example, the definition


struct node {
int data;
struct node *nextPtr;
}; // end struct node
defines a type, struct node.
A structure of type struct node has two members

integer member data and pointer member nextPtr.
Dynamic Memory Allocation (Cont.)

Function malloc takes as an argument the number
of bytes to be allocated



returns a pointer of type void * (pointer to void) to the
allocated memory.
Function malloc is normally used with the
sizeof operator.
A void * pointer may be assigned to a variable of
any pointer type.
Dynamic Memory Allocation (Cont.)

For example, the statement
newPtr = malloc( sizeof( struct node ) );




evaluates sizeof(struct node) to determine the size
in bytes of a structure of type struct node,
allocates a new area in memory of that number of bytes
and stores a pointer to the allocated memory in variable
newPtr.
The allocated memory is not initialized.
If no memory is available, malloc returns NULL.
Dynamic Memory Allocation (Cont.)

Function free deallocates memory


To free memory dynamically allocated by the
preceding malloc call, use the statement


the memory is returned to the system so that it can be
reallocated in the future.
free( newPtr );
C also provides functions calloc and realloc
for creating and modifying dynamic arrays.


calloc allocates multiple blocks of storage, each of the
same size.
realloc changes the already allocated memory size.
Memory Leak


When using malloc test for a NULL pointer return
value.
Memory Leak: Not returning dynamically allocated
memory when it’s no longer needed can cause system
to run out of memory prematurely. This is known as
“memory leak”.

Use free to return the memory to system.
Memory Allocation Process

C programming language manages memory statically,
automatically, or dynamically.
Local Variables, Automatic
variables, Function Calls
Stack
Free/Dynamic Memory
Heap
Global & Static Variables
C Program Instructions
Permanent
Storage Area
Conceptual view of storage of a C program in memory
Linked Lists

A linked list is a linear collection of self-referential
structures


A linked list is accessed via a pointer to the first node
of the list.



known as nodes, connected by pointer links.
Subsequent nodes are accessed via the link pointer member
stored in each node.
The link pointer in the last node of a list is set to NULL to
mark the end of the list.
Data is stored in a linked list dynamically

each node is created as necessary.
Linked Lists Functions


The primary functions of linked lists are insert and
delete.
Function isEmpty


If the list is empty, 1 is returned; otherwise, 0 is returned.
Function printList prints the list.
Insert Example
Function insert
Function insert
delete Example
Function delete
Function delete
Function printList
Linked List Practice Exercise

Printing the elements of a Linked List in reverse: Write
a C program to print the linked list elements in reverse
order



Either using a data structure discussed in the class
Or using recursive function calls
Inserting into an Ordered List: Write a C program to
insert 25 random integers from 0 to 100 in descending
order in a linked list.
Stacks





A stack can be implemented as a constrained version
of a linked list.
New nodes can be added to a stack and removed
from a stack only at the top.
For this reason, a stack is referred to as a last-in,
first-out (LIFO) data structure.
A stack is referenced via a pointer to the top element
of the stack.
The link member in the last node of the stack is set
to NULL to indicate the bottom of the stack.
Stack Functions



The primary functions of stacks are push and pop.
Function isEmpty tests if stack is empty.
Function printList prints the stack elements.
push operation
Function push
pop operation
Function pop
Applications of Stacks

Balancing symbols





Compiler checks for program syntax errors
Every right brace, bracket, and parenthesis must
correspond to its left counterpart
The sequence [()] is legal, but [(]) is wrong
Infix to Postfix Conversion
Postfix Expressions Evaluations
Stack Exercise

Think of using Stack to implement Linked List function


Think of using Stack to implement Queue function


printListReverse(): printing linked list elements in reverse
order
enqueue and dequeue.
Write a C program to implement push and pop.
Queues





Queue is another common data structure.
A queue is similar to a checkout line in a grocery
store—the first person in line is serviced first, and
other customers enter the line only at the end and
wait to be serviced.
Queue nodes are removed only from the head of the
queue and are inserted only at the tail of the queue.
For this reason, a queue is referred to as a first-in,
first-out (FIFO) data structure.
The insert and remove operations are known as
enqueue and dequeue, respectively.
Queue Functions



The primary functions of queues are enqueue and
dequeue.
Function isEmpty tests if queue is empty.
Function printList prints the queue elements.
Operation enqueue

The dotted arrows in part (b) illustrate Steps 2 and 3
of function enqueue that enable a new node to be
added to the end of a queue that is not empty.
Function enqueue
Operation dequeue

Part (b) shows tempPtr pointing to the dequeued node,
and headPtr pointing to the new first node of the
queue.

Function free is used to reclaim the memory pointed to by
tempPtr.
Function dequeue
Queue Exercise

Implement the level order binary tree traversal using
queue data structure.


Write the pseudo code of this algorithm.
Write a C program to implement enqueue and
dequeue.
Level Order Binary Tree Traversal


Use the Queue data structure to control the output of
the level order binary tree traversal.
Algorithm


Insert/enqueue the root node in the queue
While there are nodes left in the queue,




Get/dequeue the node in the queue
Print the node’s value
If the pointer to the left child of the node is not null
 Insert/enqueue the left child node in the queue
If the pointer to the right child of the node is not null
 Insert/enqueue the right child node in the queue
Implementing linked list, stack, queue functions
Trees


Binary Trees
Binary Search Tree



insertNode, deleteNode
inOrder, preOrder, postOrder
Applications

Duplicate elimination, Searching etc
Trees



Linked lists, stacks and queues are linear data
structures.
A tree is a nonlinear, two-dimensional data
structure with special properties.
Tree nodes contain two or more links.
Trees
Binary Search Tree (BST)

Binary Search Tree (BST)



Binary search tree (BST) is a tree where: For any node n,
items in left subtree of n  item in node n  items in right
subtree of n
Average depth of a BST is O(logN)
Operations: Insert, Delete, Search, FindMin, FindMax,
traversals
Which one is a BST?
Function insertNode
Function insertNode
Tree Traversals

Binary Tree Traversals

Pre-order traversal: root, left, right


In-order traversal: left, root, right

Post-order traversal: left, right, root


The work at a node is performed before (pre) its children are
processed
The work at a node is performed after (post) its children are
evaluated
Constructing a Binary Tree form pre-order, in-order
and post-order traversals
Tree Exercise:

Construct a Binary Tree from given in-order and preorder tree traversals output:

The inOrder traversal of the tree is: left, root, right


6 13 17 27 33 42 48
The preOrder traversal of the tree is: root, left, right

27 13 6 17 42 33 48
Tentative Midterm Exam#1 Structure

Part I: Conceptual Questions


Short answer, Fill-in-the-blank, Multiple-choice, and
True/False ( 30 pts )
Part II: Programming Questions


Write C code ( 70 pts )
4 programming questions mainly on data structures

Tips:


Deitel & Deitel book (Read and re-read Chapter 12).
Practice the Self-Review Exercises and Exercises from
Chapter 12 in the textbook.
Good Luck !