Stack and Queue This lecture prepared by the
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
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 This lecture prepared by the instructors at the University of Manitoba in Canada and has been modified by Dr. Ahmad Reza Hadaegh
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
Abstract Data Types u Two common introductory ADT that worth studying are: v Stack and v Queue u 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
Stack ADT u. A stack is an ADT with specific properties and operations
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
Stack ADT u Stack operations are: – Push - put a new item on the top of the stack – Pop - remove top item from stack v Can’t pop an empty stack – Top - examine top item without modifying stack v Can’t top an empty stack – Init - Set existing stack to empty
Stack ADT u Two more possible operations: – Full - determine if stack has reached capacity v Implementation? – Empty - determine if stack is empty
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} )
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 it’s a match, pop the stack – If not, report illegal bracketing
Stack ADT v If the stack is prematurely empty, report illegal bracketing v If there are items left on the stack after the expression has been scanned, report illegal bracketing
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 ();
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; Don’t care about stack implementation can focus attention instead on how to solve the problem
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
Stack ADT if (!bracket_stack. empty()) valid = false; if (valid) cout << “Bracketing -- GOOD” << endl; else cout << “Bracketing -- BAD” << endl; } // main
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 <See Example 1>
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
More Stacks – When computing arithmetic expressions, it’s sometimes useful to represent them using postfix (operator after) or prefix (operator before) notation
More Stacks Prefix Infix Postfix -61 6 -1 61 - *+432 (4 + 3) * 2 43+2* /+23 -94 (2 + 3) / (9 - 4) 23+94 -/ It’s easy to evaluate postfix and prefix expressions using a stack -- in part because no brackets are necessary
More Stacks – E. g. prefix postfix -61 61 evaluate 6 1 - 5 (push, pop, apply, push, ) 1 6 5 (push, pop, apply, push, )
More Stacks v E. g. prefix postfix *+432 43+2* evaluate 4 3 + 7 2 2 * 14 (push, pop, apply, push) 3 4 2 + 7 7 * 14 (push, pop, apply, push)
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
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.
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. v 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
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
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
Queues . . Data In Data Out Queue tail head
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
Queues u 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
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. . .
Queues Cashier
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 <See Example 2>
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. . .
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
- Slides: 34