Title: By Dawn J' Lawrie
1Stacks
2The STL Class stack
- Provides a size function
- Has two data type parameters
- T, the data type for the stack items
- Container, the container class that the STL uses
in its implementation of the STL stack - Uses the keyword explicit in the constructor to
prevent invoking the constructor with the
assignment operator
3Application Algebraic Expressions
- When the ADT stack is used to solve a problem,
the use of the ADTs operations should not depend
on its implementation - To evaluate an infix expression
- Convert the infix expression to postfix form
- Evaluate the postfix expression
4Evaluating Postfix Expressions
- A postfix calculator
- When an operand is entered, the calculator
- Pushes it onto a stack
- When an operator is entered, the calculator
- Applies it to the top two operands of the stack
- Pops the operands from the stack
- Pushes the result of the operation on the stack
5Evaluating Postfix Expressions
Figure 6.8 The action of a postfix calculator
when evaluating the expression 2 (3 4)
6Evaluating Postfix Expressions
- To evaluate a postfix expression which is entered
as a string of characters - Simplifying assumptions
- The string is a syntactically correct postfix
expression - No unary operators are present
- No exponentiation operators are present
- Operands are single lowercase letters that
represent integer values
7Exercise
- Evaluate the following postfix expressions by
using the algorithm just discussed. Assume the
following values for the identifiers a 7 b
3 c 12 d -5 e 1. - abc-
- abc-de
8Converting Infix Expressions to Equivalent
Postfix Expressions
- An infix expression can be evaluated by first
being converted into an equivalent postfix
expression - Facts about converting from infix to postfix
- Operands always stay in the same order with
respect to one another - An operator will move only to the right with
respect to the operands - All parentheses are removed
9Converting Infix Expressions to Equivalent
Postfix Expressions
Figure 6.9 A trace of the algorithm that converts
the infix expression a - (b c d)/e to postfix
form
10Pseudocode Algorithm
- for (each character ch in the infix expression)
- switch (ch)
- case operand // append operand to end of PE
- postfixExp postfixExp ch
- break
- case '('
- aStack.push(ch)
- break
- case ')'
- while (top of stack is not '(')
- postfixExp postfixExp (top of aStack)
- aStack.pop()
-
- aStack.pop() // remove the open
parenthesis - break
11Pseudocode Algorithm
- case operator
- while (!aStack.isEmpty and top of stack is not
'(' and -
precendence(ch) lt precendence(top of aStack)) - postfixExp postfixExp (top of aStack)
- aStack.pop()
-
- aStack.push(ch) // save new operator
- break
-
-
- // append to postfixExp the operators remaining
in the stack - while (!aStack.isEmpty())
- postfixExp postfixExp (top of aStack)
- aStack.pop()
12Exercise
- Convert the following infix expressions to
postfix form using the algorithm just discussed - a-bc
- a-(bcd)/e
13Application A Search Problem
- High Planes Airline Company (HPAir)
- For each customer request, indicate whether a
sequence of HPAir flights exists from the origin
city to the destination city - The flight map for HPAir is a graph
- Adjacent vertices are two vertices that are
joined by an edge - A directed path is a sequence of directed edges
14Application A Search Problem
Figure 6.10 Flight map for HPAir
15A Nonrecursive Solution That Uses a Stack
- The solution performs an exhaustive search
- Beginning at the origin city, the solution will
try every possible sequence of flights until
either - It finds a sequence that gets to the destination
city - It determines that no such sequence exists
- Backtracking can be used to recover from a wrong
choice of a city
16A Nonrecursive Solution That Uses a Stack
Figure 6.13 A trace of the search algorithm,
given the flight map in Figure 6-10
17A Recursive Solution
- Possible outcomes of the recursive search
strategy - You eventually reach the destination city and can
conclude that it is possible to fly from the
origin to the destination - You reach a city C from which there are no
departing flights - You go around in circles
18A Recursive Solution
- A refined recursive search strategy
- searchR(in originCityCity,
- in destinationCityCity)boolean
- Mark originCity as visited
- if (originCity is destinationCity)
- Terminate -- the destination is reached
- else
- for (each unvisited city C adjacent to
- originCity)
- searchR(C, destinationCity)
19The Relationship Between Stacks and Recursion
- Typically, stacks are used by compilers to
implement recursive methods - During execution, each recursive call generates
an activation record that is pushed onto a stack - Stacks can be used to implement a nonrecursive
version of a recursive algorithm
20Summary
- ADT stack operations have a last-in, first-out
(LIFO) behavior - Stack applications
- Algorithms that operate on algebraic expressions
- Flight maps
- A strong relationship exists between recursion
and stacks
21Queues
22The Abstract Data Type Queue
- A queue
- New items enter at the back, or rear, of the
queue - Items leave from the front of the queue
- First-in, first-out (FIFO) property
- The first item inserted into a queue is the first
item to leave
23The Abstract Data Type Queue
- Queues
- Are appropriate for many real-world situations
- Example A line to buy a movie ticket
- Have applications in computer science
- Example A request to print a document
- A simulation
- A study to see how to reduce the wait involved in
an application
24The Abstract Data Type Queue
- ADT queue operations
- Create an empty queue
- Destroy a queue
- Determine whether a queue is empty
- Add a new item to the queue
- Remove the item that was added earliest
- Retrieve the item that was added earliest
25The Abstract Data Type Queue
- Definitions for the ADT queue operations
- createQueue()
- destroyQueue()
- isEmpty()boolean query
- enqueue(in newItemQueueItemType)throw
QueueException
26The Abstract Data Type Queue
- Definitions for the ADT queue operations
- dequeue() throw QueueException
- dequeue(out queueFrontQueueItemType) throw
QueueException - getFront(out queueFrontQueueItemType) throw
QueueException
27The Abstract Data Type Queue
Figure 7.2 Some queue operations
28Reading a String of Characters
- A queue can retain characters in the order in
which they are typed - aQueue.createQueue()
- while (not end of line)
- Read a new character ch
- aQueue.enqueue(ch)
- //end while
- Once the characters are in a queue, the system
can process them as necessary
29Recognizing Palindromes
- A palindrome
- A string of characters that reads the same from
left to right as its does from right to left - To recognize a palindrome, a queue can be used in
conjunction with a stack - A stack reverses the order of occurrences
- A queue preserves the order of occurrences
30Recognizing Palindromes
- A nonrecursive recognition algorithm for
palindromes - As you traverse the character string from left to
right, insert each character into both a queue
and a stack - Compare the characters at the front of the queue
and the top of the stack
31Recognizing Palindromes
Figure 7.3 The results of inserting a string into
both a queue and a stack
32Implementations of the ADT Queue
- An array-based implementation
- Possible implementations of a pointer-based queue
- A linear linked list with two external references
- A reference to the front
- A reference to the back
- A circular linked list with one external
reference - A reference to the back
33A Pointer-Based Implementation
Figure 7.4 A pointer-based implementation of a
queue (a) a linear linked list with two external
pointers b) a circular linear linked list with
one external pointer
34A Pointer-Based Implementation
Figure 7.5 Inserting an item into a nonempty
queue
Figure 7.6 Inserting an item into an empty queue
a) before insertion b) after insertion
Figure 7.7 Deleting an item from a queue of more
than one item
35An Array-Based Implementation
Figure 7.8 a) A naive array-based implementation
of a queue b) rightward drift can cause the
queue to appear full
36An Array-Based Implementation
- A circular array eliminates the problem of
rightward drift - A problem with the circular array implementation
- front and back cannot be used to distinguish
between queue-full and queue-empty conditions
37An Array-Based Implementation
Figure 7.11b (a) front passes back when the queue
becomes empty (b) back catches up to front
when the queue becomes full
38An Array-Based Implementation
- To detect queue-full and queue-empty conditions
- Keep a count of the queue items
- To initialize the queue, set
- front to 0
- back to MAX_QUEUE 1
- count to 0
39An Array-Based Implementation
- Inserting into a queue
- back (back1) MAX_QUEUE
- itemsback newItem
- count
- Deleting from a queue
- front (front1) MAX_QUEUE
- --count
40An Array-Based Implementation
- Variations of the array-based implementation
- Use a flag isFull to distinguish between the full
and empty conditions - Declare MAX_QUEUE 1 locations for the array
items, but use only MAX_QUEUE of them for queue
items
41An Array-Based Implementation
Figure 7.12 A more efficient circular
implementation a) a full queue b) an empty queue