Data Structures - PowerPoint PPT Presentation

1 / 42
About This Presentation
Title:

Data Structures

Description:

Examine containers (data structures) provided in C . Study data ... multimap T1, T2 Searches take O(log2n) time. C An Introduction to Computing, 3rd ed. ... – PowerPoint PPT presentation

Number of Views:99
Avg rating:3.0/5.0
Slides: 43
Provided by: steve1803
Category:

less

Transcript and Presenter's Notes

Title: Data Structures


1
Data Structures
  • Chapter 15

2
Objectives
  • Examine containers (data structures) provided in
    C
  • Study data structures stack and queue
  • Look at recursion and how it relates to stacks
  • Learn about two-dimensional linked structures
  • Take a peek at expert systems in AI

3
Introductory ExampleBinary Representation of
Integers -- Stacks
  • Consider the task of changing a base-ten number
    to another base
  • One algorithm uses repeated division by the new
    base

4
Binary Representation of Integers
  • The number in the new base is the remainders in
    reverse order of when they were generated
  • The problem is how to outputthe numbers
    inreverse order

5
The Stack Container
  • We need to store the digits in a
    Last-In-First-Out order type a list
  • Such a list is the stack
  • Also called a push-down stack
  • Visualize a spring loaded stack of plates

6
The Stack Container
  • Operations on a stack
  • empty() Returns true/false
  • top() Returns top value
  • push(v) Adds value v to top
  • pop() Removes value at top

7
Base-Conversion Algorithm
  • 1. Create an empty stack to hold the remainders.
  • 2. While number ? 0, do the following
  • a. Calculate the remainder that results when
    number is divided by base.
  • b. Push remainder onto the stack of remainders.
  • c. Replace number by the integer quotient of
    number divided by base.
  • 3. Declare result as an empty string.
  • 4. While the stack of remainders is not empty, do
    the following
  • a. Remove the remainder from the top of the
    stack of remainders.
  • b. Convert remainder to its base-base
    equivalent.
  • c. Concatenate the base-base equivalent of
    remainder to result.

8
Base-Conversion Algorithm
  • Remainders stored in the stack

9
Base-Conversion Algorithm
  • The answer is generated by repeatedly
  • Looking at the value of the top
  • And then popping it off to make the next one
    available
  • Note the source codewhich implementsthe
    algorithm, Figure 15.2

10
The stackltTgt Adapter
  • The adapter is a component that acts as a
    "wrapper" around another component
  • Gives it a new interface
  • To build a stack using one of the other
    containersstack ltint, listltintgt gt intListStack

11
The stackltTgt Adapter
  • Features of intListStack
  • Uses memory more efficiently than the default
    stackltTgt implementation
  • Will be slightly slower for push() and pop()
  • Could also create stackltint, vectorltintgt gt
    intVectorStack

12
The stackltTgt Methods
  • void push (T aVal) Place aVal on top
  • void pop() Remove top value
  • T top() Retrieve (but not remove) top
    value
  • bool empty() Return true if stack contains
    no values

13
Queues
  • A container in which values are always
  • Added at one end, the rear or tail
  • Removed from the opposite end, the front or head
  • Examples
  • A line at the supermarket checkout
  • A line of vehicles at a toll booth

14
The queueltTgt Adapter
  • The default adapter is the dequeltTgt
  • Which allows push/pop at either end
  • Possible to use different adapter
  • queueltstring, listltstringgt gt stringListQueue
  • A queue where strings are stored in a list
  • Note queueltTgt cannot wrap vectorltTgt

15
The queueltTgt Methods
  • bool empty() Return true if no values
  • void push (T aVal) Append aVal to end
  • void pop() Retrieve (but not remove) value
    at front
  • T front() Retrieve (but not remove) value
    at front
  • T back() Retrieve (but not
  • remove) value at back of queue

16
The dequeltTgt Container
  • Stands for double-ended queue
  • Good for problems with a sequence of values which
    manipulates values at either end of sequence
  • Additional methods
  • void push_back(T aVal)
  • void pop_back()
  • void push_front(T aval)
  • void pop_front()
  • int size()

Note table of O( ) comparisons, pg. 912
17
The priority_queueltTgt Container
  • A queue where the order of the values is not
    necessarily determined by FIFO
  • Ordering depends on a specified value of each
    element
  • Operating system uses priority queue
  • Decides which process runs next
  • Determines which print job is handled next
  • Note contrast between queueltTgt and
    priority_queueltTgt, Figure 15.3

18
Recursion
  • When a function calls itself
  • Can be applied to stacks
  • Consider raising a value to a power
  • It can be defined recursively

19
Recursion
  • Recursive function which raises a number to an
    integer power
  • double power(double x, int n)
  • if (n 0)
  • return 1.0 //anchor case
  • else if (n gt 0) //inductive step (n gt 0)
  • return power (x, n - 1) x else //
    invalid parameter n
  • cerr ltlt " power(x,n) n is negative.\n"
  • return -1.0

20
Recursion
  • Each time the function calls itself the operating
    system generates an activation record
  • That record is pushed onto a stack
  • When each call finishes it is popped off

21
An Introduction to Trees
  • Recall advantage of linked lists over arrays
  • Values can be inserted anywhere in the list
  • No need to shift values to make room
  • Weakness of linked lists
  • Only first or last element can be easily accessed
    directly
  • Must traverse list to find desired element
  • Search algorithms for arrays
  • Linear
  • Binary (required sorted array)

22
An Introduction to Trees
  • We seek a linked data structure so elements can
    be searched more quickly
  • Strategy
  • Start with middle element of a list
  • Create a link to that middle element

23
An Introduction to Trees
  • From that middle element
  • Create two links
  • One each to middle element of sub lists
  • Then from each of those, links to remaining
    sublists

24
An Introduction to Trees
  • Resulting structure redrawn
  • Note resemblance of a tree

25
Tree Terminology
26
Example Tree
  • A genealogical tree

27
Example Tree
  • A parse tree
  • Used to check the syntax of an expression

28
Binary Tree
  • A tree where each node has at most two children

Here showing the possible outcomes of flipping a
coin three times
29
Binary Tree
  • Could also be used to model Morse code

30
Implementing Binary Trees
  • Represented by a multiply linked structure
  • Each node has two links
  • One link to left child
  • Second link to right child

template lttypename DataTypegt . . . class Node
public //... Constructors and methods go here
DataType myValue Node myLeft Node
myRight
31
Implementing Binary Trees
  • Node class specified as a private element of our
    BinaryTree class

template lttypename DataTypegt class BinaryTree
public // ... constructors and methods go
here private class Node
pubic // ... Node constructors and methods
DataType myValue Node myLeft Node
myRight // ... BinaryTree instance
variables go here
32
Implementing Binary Trees
  • The class specified could be given this binary
    tree and

33
Implementing Binary Trees
  • Represent the tree with the following structure

34
Binary Search Trees
  • The value in each node is
  • Greater than all the values in its left subtree
    (if there are any)
  • Less than all the values in its right subtree(if
    there are any)
  • A binary search tree can be searched quickly

35
Binary Search Tree Algorithm
1. Initialize a pointer currentNode to the node
containing the root and found to false. 2.
While currentNode is not null and found is false,
do the following If the item
being sought is Less than the value referred
to by
currentNode-gtmyValue Set currentNode
currentNode-gtmyLeft Greater than the value
referred to by
currentNode-gtmyValue Set currentNode
currentNode-gtmyRight Else Set found
to true.
Note BST search() method, Figure 15.5
36
Tree Traversals
  • Moving through the binary tree
  • Visit each node exactly once
  • Recursive scheme
  • Visit the root and process its contents
  • Traverse the left subtree
  • Traverse the right subtree

37
Tree Traversals
  • Varying order of NRoot, LLeft, and RRight
    subtrees can give different results
  • Three (of the six) orders have names
  • LNR ? Inorder
  • NLR ? Preorder
  • LRN ? Post order
  • Used for manipulatingexpression trees

38
Manipulating Binary Search Trees
  • Inorder traversal visits the nodes of a BST in
    ascending order, Figure 15.6 shows a print method
  • Insert method, Figure 15.7

Note how insert() method is used to insert a 35
into the BST
39
Trees in STL
  • The STL does not provide templates with Tree in
    their name
  • Some of its containers are generally built using
    a self-balancing binary search tree
  • setltTgt
  • map ltT1, T2gt
  • multisetltTgt
  • multimap ltT1, T2gt

Searches take O(log2n) time
40
Expert Systems
  • Consider the children's game of "Animal"
  • The player thinks of an animal
  • The guesser asks a series of yes-no questions in
    order to try to determine the animal
  • If the guesser cannot fully identify the animal,
    he/she asks questions which uniquely identify the
    animal
  • A computer program which can play this game is
    said to display "artificial intelligence"

41
Expert Systems
  • The program maintains a knowledge base of
    questions
  • Allows it to eliminate animals from consideration
  • If it guesses right, it wins
  • Otherwise it asks for the name of the animal and
    asks for a way to distinguish between it's best
    guess and the true answer
  • Thus the knowledge base grows
  • Programs that exhibit expertise in some area
    through a knowledge base are known as expert
    systems

42
Expert Systems
  • View a program which plays the animal game,
    Figure 15.8
  • It builds a special tree for its knowledge base
Write a Comment
User Comments (0)
About PowerShow.com