# chapter 05 compiled by: dr. mohammad omar alhawarat stacks & queues

Post on 28-Dec-2015

220 views

Embed Size (px)

TRANSCRIPT

Stacks

Chapter 05Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues 1OverviewStacks and Queues Data structure holding a collection of objects, ordered by when they were inserted into the structure.Stack can access newest object.Queue can access oldest object.22Stacks3A stack is a linear collection whose elements are added and removed from the same endStacks are processed in a last in, first out (LIFO) mannerUsually, stacks are depicted vertically, and we refer to the top of the stack as the end to which elements are added and removedStack Operations4push: places an element onto the top of a stackpop: removes an element from the top of the stackpeek: which retrieves (copies) a value from the top of the stack without removing itisempty: an operation to determine whether or not the stack is emptyempty: an operation to empty out a stackThe Stack Interface

55The Stack InterfaceIast-in, first-out or LIFO policyLast item pushed on the stack is next item popped off the stack.Example:A stack of plates.66The Stack Interface

77Push8Push means place a new data element at the top of the stack

17 5 11 3Push (cont.)9Push means place a new data element at the top of the stack

17 5 11 3Push (cont.)10Push means place a new data element at the top of the stack

17 5 11 3Push (cont.)11Push means place a new data element at the top of the stack

17 5 11 3Pop12Pop means take a data element off the top of the stack

17 5 11 3Pop (cont.)13Pop means take a data element off the top of the stack

17 5 11 3Pop (cont.)14Pop means take a data element off the top of the stack

17 5 11 3Pop (cont.)15Pop means take a data element off the top of the stack

17 5 11 3Peek16Peek means retrieve the top of the stack without removing it

17 5 11 3Peek (cont.)17Peek means retrieve the top of the stack without removing it

17 5 11 3 3Peek (cont.)18Peek means retrieve the top of the stack without removing it

17 5 11 3 3Linked-List Stack19Stacks can be implemented with a linked listThe front node is the top of the stackLinked-List Stack (cont.)20 topTo pop, we remove the node at the front of the linked list, and return the element to the clientLinked-List Stack (cont.)21 topTo pop, we remove the node at the front of the linked list, and return the element to the clientLinked-List Stack (cont.)22 topTo push, we place the new element in a node and insert it at the front of the linked listThe Program (Call) StackWhen a method is calledRuntime environment creates activation recordShows method's state during executionActivation record pushed onto the program stack (Java stack)Top of stack belongs to currently executing methodNext method down is the one that called current method2323The Program StackThe program stack at 3 points in time; (a) when main begins execution; (b) when methodA begins execution, (c) when methodB begins execution.

2424Evaluating Postfix Expressions25Before looking further at the implementation of a stack, let's first see how one might be usedArithmetic operations are traditionally written in infix notation, meaning that the operator is placed between its operands in the form When evaluating infix expressions, we rely on precedence rules to determine the order of operator evaluationIn a postfix expression, the operator comes after its two operands Evaluating Postfix Expressions26The process of evaluating a postfix expression can be stated simply:scan from left to right,apply each operation to the two previous operands immediately preceding it andreplace the operator with the resultConsider the infix expression: 4 + 5 * 2In postfix notation, it would be written as: 4 5 2 * +Evaluating Postfix Expressions27Consider the design of a program that can compute the result of a postfix expressionThe evaluation rule relies on being able to retrieve the previous two operands whenever we encounter an operatorA large postfix expression will have many operators and operands to manageA stack is the perfect collection to use in this solutionEvaluating Postfix Expressions28Solution algorithm:scan the expression from left to right, identifying each token as an operator or operandif the scanned token is an operand, push it onto the stackif the scanned token is an operatorpop the top two elements off the stack,apply the operation to them, andpush the result onto the stackIf we reach the end of the expression the remaining element on the stack is the result of the expression (otherwise the expression was not well formed)Using a Stack to Evaluate a Postfix Expression29Given the expression: 7 4 -3 * 1 5 + / *7top4-3*15+/-126-2-14*Infix-to-Postfix AlgorithmSymbol in Infix ActionOperandAppend to end of output expressionOperator ^Push ^ onto stackOperator +,-,*, or /Pop operators from stack, append to output expression until stack empty or top has lower precedence than new operator. Then push new operator onto stackOpen parenthesisPush ( onto stackClose parenthesisPop operators from stack, append to output expression until we pop an open parenthesis. Discard both parentheses.3030Transforming Infix to Postfix Steps to convert the infix expression a / b * ( c + ( d e ) ) to postfix form.

3131Evaluating Postfix ExpressionFig. 21-10 The stack during the evaluation of the postfix expression a b / when a is 2 and b is 4

3232Evaluating Postfix ExpressionFig. 21-11 The stack during the evaluation of the postfix expression a b + c / when a is 2, b is 4 and c is 3

3333Evaluating Infix ExpressionsTwo stacks during evaluation of a + b * c when a = 2, b = 3, c = 4; (a) after reaching end of expression;(b) while performing multiplication; (c) while performing the addition

3434Performance and LimitationsPerformanceLet n be the number of elements in the stackThe space used is O(n)Each operation runs in time O(1)LimitationsThe maximum size of the stack must be defined a priori and cannot be changedTrying to push a new element into a full stack causes an implementation-specific exceptionStacks3535QUEUES36Definition: A sequence of elements of the same type. The first stored element is first accessible.The structure is known also under the name FIFO - first in first out

Basic operations37EnQueue : store a data item at the end of the queue

DeQueue : retrieve a data item from the beginning of the queueThe Queue InterfaceQueueVery similar to a stack.Items are inserted in one end (the back) and removed from the other end (the front).first-in, first-out, or FIFO3838The Queue Interface

3939Array Implementation of a Queue40Similar to the linked-list queue, there are two data members called front and back, but they are indexes into an Array instead of pointersWhen enqueuing, the back index is incremented, and when dequeuing, the front index is incremented40Enqueue / Dequeue41 0 1 2 3 4 5 6 7frontbackEnqueue / Dequeue (cont.)42frontbackDEQUEUE 0 1 2 3 4 5 6 7Enqueue / Dequeue (cont.)43frontbackDEQUEUE 0 1 2 3 4 5 6 7Enqueue / Dequeue (cont.)44frontbackDEQUEUE 0 1 2 3 4 5 6 7Enqueue / Dequeue (cont.)45frontbackDEQUEUE 0 1 2 3 4 5 6 7Enqueue / Dequeue (cont.)46frontbackENQUEUE 0 1 2 3 4 5 6 7Enqueue / Dequeue (cont.)47 0 1 2 3 4 5 6 7frontbackENQUEUEEnqueue / Dequeue (cont.)48 0 1 2 3 4 5 6 7frontbackENQUEUEEnqueue / Dequeue (cont.)49 0 1 2 3 4 5 6 7frontbackENQUEUE50 0 1 2 3 4 5 6 7frontbackDEQUEUEEnqueue / Dequeue (cont.)51 0 1 2 3 4 5 6 7frontbackDEQUEUEEnqueue / Dequeue (cont.)52 0 1 2 3 4 5 6 7frontbackDEQUEUEEnqueue / Dequeue (cont.)53 0 1 2 3 4 5 6 7frontbackDEQUEUEEnqueue / Dequeue (cont.)54 0 1 2 3 4 5 6 7frontbackENQUEUEEnqueue / Dequeue (cont.)55 0 1 2 3 4 5 6 7frontbackENQUEUEEnqueue / Dequeue (cont.)56 0 1 2 3 4 5 6 7frontbackDEQUEUEEnqueue / Dequeue (cont.)57 0 1 2 3 4 5 6 7frontbackDEQUEUEEnqueue / Dequeue (cont.)58 0 1 2 3 4 5 6 7frontbackDEQUEUEEnqueue / Dequeue (cont.)59 0 1 2 3 4 5 6 7frontbackENQUEUEEnqueue / Dequeue (cont.)60 0 1 2 3 4 5 6 7frontbackENQUEUE?Enqueue / Dequeue (cont.)61 0 1 2 3 4 5 6 7frontbackENQUEUEWe could double the size of the array here.Enqueue / Dequeue (cont.)62 0 1 2 3 4 5 6 7frontbackENQUEUEBut if we keep doing this, we may have a million elements in the Array, but only a few at the end are used!Enqueue / Dequeue (cont.)63 0 1 2 3 4 5 6 7frontbackENQUEUEWe handle this problem by having the back wrap around to the beginning of the array.Enqueue / Dequeue (cont.)64 0 1 2 3 4 5 6 7frontbackENQUEUEEnqueue / Dequeue (cont.)65 0 1 2 3 4 5 6 7frontbackThe front also wraps to the beginning when it reaches the end of the arrayEnqueue / Dequeue (cont.)How Do We Know When the Array is Full?66We may still need to double the capacity of the array if it gets filledAn array will be full whenback + 1 == frontORback + 1 == capacity AND front == 0 66A Full Array67 0 1 2 3 4

Recommended