Sei sulla pagina 1di 34

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

National University

Page 1

Abstract Data Types


u

You have been introduced to some of the benefits of implementing programs with C++ classes such as
Data and function hiding Reusability and reliability

National University

Page 2

Abstract Data Types


u

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 v Data structure is exclusively manipulated by operations, and operations work exclusively on data structure

National University

Page 3

Abstract Data Types


u

Two common introductory ADT that worth studying are:


v
v

Stack Queue

and

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
National University
Page 4

Stack ADT

A stack is an ADT with specific properties and operations

National University

Page 5

Stack ADT
u

Stack properties are:


Only one item can be accessed at a time v Always the last item inserted (LIFO) New items must be inserted at the top The size of the stack is dynamic v The stack must be able to grow and shrink Implementation? Normally, items stored on the stack are homogeneous

National University

Page 6

Stack ADT
u

Stack operations are:


Push - put a new item on the top of the stack Pop - remove top item from stack v Cant pop an empty stack Top - examine top item without modifying stack v Cant top an empty stack Init - Set existing stack to empty

National University

Page 7

Stack ADT

Two more possible operations:


Full - determine if stack has reached capacity v Implementation? Empty - determine if stack is empty

National University

Page 8

Stack ADT
u

Many problems can be solved using stacks


Given a mathematical expression with 3 types of brackets v () [] {} Determine if the brackets are properly matched { 5 * (8-2) } / { [4 * (3+2)] + [5 * 6] } OK! { (A+C) * D

Not OK!
[ A + {B+C} )
National University
Page 9

Stack ADT
This is easily solved with a stack Algorithm: v Scan expression from left to right v Each time a left bracket is encountered, push it onto the stack v When a right bracket is encountered, compare it to the top item on the stack If its a match, pop the stack If not, report illegal bracketing
National University
Page 10

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

National University

Page 11

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

National University

Page 12

Stack ADT
// Stack routines included here for stack of characters void main () { char curr, temp; bool valid = true;

// Assume expression has valid // bracketing cstack bracket_stack; Dont care about stack implementation can focus attention instead on how to solve the problem
National University
Page 13

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
National University
Page 14

Stack ADT

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

National University

Page 15

Stack ADT
u

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

National University

Page 16

More Stacks
u

Consider the problem of evaluating an arithmetic expression using a stack


Traditionally, when we write an arithmetic expression as follows v 2 + 3 * (6 - 5) This is known as infix notation v Operators are in-between the operands

National University

Page 17

More Stacks

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

National University

Page 18

More Stacks
Prefix -61
*+432 /+23-94

Infix 6-1
(4 + 3) * 2 (2 + 3) / (9 - 4)

Postfix 6143+2* 23+94-/

Its easy to evaluate postfix and prefix expressions using a stack -- in part because no brackets are necessary
National University
Page 19

More Stacks
E.g.
prefix -61 evaluate 6 1 5 1 6 5 postfix 61-

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

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


Page 20

National University

More Stacks
v

E.g.
postfix
43+2* evaluate

prefix
*+432 4 3 + 7 2 2

14

3 4

2 + 7 7

* 14

(push, push, push, pop, pop, apply, push, pop, pop, apply, push)
National University

(push, push, pop, pop, apply, push, push, pop, pop, apply, push)
Page 21

More Stacks
Algorithm for evaluating postfix v Parse expression from left to right v When an operand is encountered, push it onto the stack v When an operator is encountered, pop the top two operands, apply the operator, and push the result onto the stack v When the expression is completely scanned, the final result will be on the stack Code left as an exercise v Very straight-forward if stack already exists
National University
Page 22

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: v Scan infix string from left to right v Each time an operand is encountered, copy it to the output v When a bracket is encountered, check its orientation.

National University

Page 23

More Stacks
Push left brackets onto the stack If its 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
National University
Page 24

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

National University

Page 25

Queues
u

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 v The first item placed on the queue is always the first one removed
National University
Page 26

Queues

Data In

....
Queue
tail head

Data Out

National University

Page 27

Queues
u

Possible operations
Init v Initializes a queue so as to be empty Insert v Adds a new item to the tail of the queue Remove v Removes the item at the head of the queue Empty v Tests to see if the queue is empty Full v Tests to see if the queue is full
National University
Page 28

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

National University

Page 29

Queues

Can be modified to suit the needs of specific problems v Priority queues A not quite so democratic queue (more in a bit) Are all around us ...

National University

Page 30

Queues

Cashier

National University

Page 31

Queues
u

Queues are common in computing


Scheduling queues v Operating systems support multi-tasking by sharing scarce resources such as CPU time v Each task that requests CPU resources might be put in a queue v Tasks are given cycles of time If task finishes . good -- if not, task goes to back of queue for additional cycles
National University
Page 32

Queues
Multiple queues v 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 v The same idea as a priority queue ...

National University

Page 33

Queues
UNIX uses a priority queue to schedule processes v 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
National University
Page 34

Potrebbero piacerti anche