+ All Categories
Home > Documents > 05 (Stack Queue)

05 (Stack Queue)

Date post: 08-Apr-2016
Category:
Upload: frankjamison
View: 17 times
Download: 3 times
Share this document with a friend
Description:
C++ Stack and Queue presentation
34
Page 1 National University Stack and Queue This lecture prepared by the instructors at the University of Manitoba in Canada and has been modified by Dr. Ahmad Reza Hadaegh
Transcript
Page 1: 05 (Stack Queue)

Page 1National University

Stack and

QueueThis lecture prepared by the instructors at the University of Manitoba in Canada and has

been modified by Dr. Ahmad Reza Hadaegh

Page 2: 05 (Stack Queue)

Page 2National University

Abstract Data Types

You have been introduced to some of the benefits of implementing programs with C++ classes such as

– Data and function hiding– Reusability and reliability

Page 3: 05 (Stack Queue)

Page 3National University

Abstract Data Types

A C++ class is often the manner in which an abstract data type (ADT) is implemented– An ADT is a data structure together with a set of

defined operations Data structure is exclusively manipulated by

operations, and operations work exclusively on data structure

Page 4: 05 (Stack Queue)

Page 4National University

Abstract Data Types Two common introductory ADT that worth studying

are:

Stack and Queue

Many problems (or parts of problems) can be thought of as stack problems, queue problems, or other problems that can be solved with the help of another (perhaps user-defined) ADT

– Decide what ADTs you need, build them, test them, then tackle your larger problem

Page 5: 05 (Stack Queue)

Page 5National University

A stack is an ADT with specific properties and operations

Stack ADT

Page 6: 05 (Stack Queue)

Page 6National University

Stack ADT

Stack properties are:– Only one item can be accessed at a time

Always the last item inserted (LIFO)– New items must be inserted at the top– The size of the stack is dynamic

The stack must be able to grow and shrink– Implementation?

– Normally, items stored on the stack are homogeneous

Page 7: 05 (Stack Queue)

Page 7National University

Stack ADT

Stack operations are:– Push - put a new item on the top of the stack– Pop - remove top item from stack

Can’t pop an empty stack– Top - examine top item without modifying stack

Can’t top an empty stack– Init - Set existing stack to empty

Page 8: 05 (Stack Queue)

Page 8National University

Stack ADT

Two more possible operations:– Full - determine if stack has reached capacity

Implementation?– Empty - determine if stack is empty

Page 9: 05 (Stack Queue)

Page 9National University

Stack ADT Many problems can be solved using stacks

– Given a mathematical expression with 3 types of “brackets” ( ) [ ] { }

Determine if the brackets are properly matched

{ 5 * (8-2) } / { [4 * (3+2)] + [5 * 6] }

{ (A+C) * D

[ A + {B+C} )

OK!

Not OK!

Page 10: 05 (Stack Queue)

Page 10National University

Stack ADT

– This is easily solved with a stack– Algorithm:

Scan expression from left to right Each time a left bracket is encountered, push

it onto the stack When a right bracket is encountered,

compare it to the top item on the stack– If it’s a match, pop the stack

– If not, report illegal bracketing

Page 11: 05 (Stack Queue)

Page 11National University

Stack ADT

If the stack is prematurely empty, report illegal bracketing

If there are items left on the stack after the expression has been scanned, report illegal bracketing

Page 12: 05 (Stack Queue)

Page 12National University

Stack ADT

– Assume the following member functions are available for our character stack ADT bool empty (); push (item); // Modifies stack char pop (); // Modifies stack char top ();

Page 13: 05 (Stack Queue)

Page 13National University

Stack ADT// Stack routines included here for stack of characters

void main () {

char curr, temp;bool valid = true; // Assume expression has valid

// bracketingcstack bracket_stack;

Don’t care about stack implementation -can focus attention instead on howto solve the problem

Page 14: 05 (Stack Queue)

Page 14National University

Stack ADT cin >> curr; // Assume no blanks in input expression while (curr != ‘\n’ && valid) { if (curr == ‘(’ || curr == ‘[’ || curr == ‘{’) bracket_stack.push (curr); else if (curr == ‘)’ || curr == ‘]’ || curr == ‘}’) if (bracket_stack.empty() ) then valid = false; else if (bracket_stack.pop() does not mate with curr) valid = false; cin >> curr; } // while

Page 15: 05 (Stack Queue)

Page 15National University

Stack ADT

if (!bracket_stack.empty()) valid = false; if (valid) cout << “Bracketing -- GOOD” << endl; else cout << “Bracketing -- BAD” << endl; } // main

Page 16: 05 (Stack Queue)

Page 16National University

Stack ADT

The recognition that bracket matching is a stack problem results in the solution being trivial– Solution will also have closer consistency cross

programmers– Stack can be reused in other problems– Implementation of stack can change, but

solution to bracket problem remains the same

Page 17: 05 (Stack Queue)

Page 17National University

More Stacks

Consider the problem of evaluating an arithmetic expression using a stack– Traditionally, when we write an arithmetic

expression as follows 2 + 3 * (6 - 5)

– This is known as infix notation Operators are in-between the operands

Page 18: 05 (Stack Queue)

Page 18National University

More Stacks

– When computing arithmetic expressions, it’s sometimes useful to represent them using postfix (operator after) or prefix (operator before) notation

Page 19: 05 (Stack Queue)

Page 19National University

More Stacks

Prefix Infix Postfix

- 6 1* + 4 3 2

/ + 2 3 - 9 4

6 - 1(4 + 3) * 2

(2 + 3) / (9 - 4)

6 1 -4 3 + 2 *

2 3 + 9 4 - /

It’s easy to evaluate postfix and prefix expressionsusing a stack -- in part because no brackets are necessary

Page 20: 05 (Stack Queue)

Page 20National University

More Stacks

– E.g.

prefix postfix

- 6 1

61

6 1 -

16

evaluate

- - 55

(push, push,pop, pop, apply, push,)

(push, push,pop, pop, apply, push,)

Page 21: 05 (Stack Queue)

Page 21National University

More Stacks E.g.

prefix postfix

* + 4 3 2

432

4 3 + 2 *

34

evaluate

1472

+* + 7

27 14*

(push, push, push,pop, pop, apply, push,pop, pop, apply, push)

(push, push,pop, pop, apply, push,push,pop, pop, apply, push)

Page 22: 05 (Stack Queue)

Page 22National University

More Stacks

– Algorithm for evaluating postfix Parse expression from left to right When an operand is encountered, push it

onto the stack When an operator is encountered, pop the

top two operands, apply the operator, and push the result onto the stack

When the expression is completely scanned, the final result will be on the stack

– Code left as an exercise Very straight-forward if stack already exists

Page 23: 05 (Stack Queue)

Page 23National University

More Stacks

– What if we want to convert and expression from infix to postfix?

– 2 + 3 * [(5 - 6) / 2] becomes 2 3 5 6 - 2 / * +– Use the following algorithm:

Scan infix string from left to right Each time an operand is encountered, copy it

to the output When a bracket is encountered, check its

orientation.

Page 24: 05 (Stack Queue)

Page 24National University

More Stacks

– Push left brackets onto the stack– If it’s a right bracket, pop all operators on

the stack and copy them to output until a matching left bracket is encountered. Discard the left bracket.

When an operator is encountered, check the top item of the stack.

– If the priority is >= the current operator, pop the top operator and copy it to output

– Continue until an operator of lesser priority is encountered or until stack is empty

Page 25: 05 (Stack Queue)

Page 25National University

More Stacks

– Assume left brackets have lowest priority– Finally, push current operator onto the

stack– When the end of the expression is

reached, copy the remaining stack contents to output in the order popped

Page 26: 05 (Stack Queue)

Page 26National University

Queues A queue is an ADT with the following

specific properties:– A queue contains zero or more, normally

homogenous, items– Data items are added to the tail (back) of the

queue and are removed from the head (front) of the queue

– The items in the queue are maintained in FIFO (first-in-first-out) order The first item placed on the queue is always

the first one removed

Page 27: 05 (Stack Queue)

Page 27National University

Queues

Data In Data Out

Queue

tail head

. . . .

Page 28: 05 (Stack Queue)

Page 28National University

Queues Possible operations

– Init Initializes a queue so as to be empty

– Insert Adds a new item to the tail of the queue

– Remove Removes the item at the head of the queue

– Empty Tests to see if the queue is empty

– Full Tests to see if the queue is full

Page 29: 05 (Stack Queue)

Page 29National University

Queues

Basic queues are similar to basic stacks– Similar operations– Only allow access to one data item at a time– Dynamic in nature– Have implementation dependencies

Page 30: 05 (Stack Queue)

Page 30National University

Queues

– Can be modified to suit the needs of specific problems Priority queues

– A not quite so democratic queue (more in a bit)

– Are all around us ...

Page 31: 05 (Stack Queue)

Page 31National University

Queues

Cashier

Page 32: 05 (Stack Queue)

Page 32National University

Queues

Queues are common in computing– Scheduling queues

Operating systems support multi-tasking by sharing scarce resources such as CPU time

Each task that requests CPU resources might be put in a queue

Tasks are given cycles of time– If task finishes …. good -- if not, task goes

to back of queue for additional cycles

Page 33: 05 (Stack Queue)

Page 33National University

Queues

– Multiple queues Might have many queues, each of which

have different priority– Before second queue is processed, all

jobs in first queue must be processed– Before third queue is processed, all

jobs in second queue must be processed, etc

The same idea as a priority queue ...

Page 34: 05 (Stack Queue)

Page 34National University

Queues

– UNIX uses a priority queue to schedule processes Priority is based upon many factors

– The “niceness” of the processes– A number from 0-127 (127 being very

nice to other users)– See “man nice”

– Recent CPU usage of process– Time process has been waiting for a cycle

A priority queue is somewhat like a cross between a table and a queue


Recommended