stack as an adt

27
stack as an ADT A stack isan ordered collection of data items accessispossible only atone end (top ofthe stack). Basic operations 1. Constructa stack (usually em pty) 2. Check ifstack isem pty 3. Push: A dd an elem entatthe top ofthe stack 4. Top: Retrieve the top elem entofthe stack 5. Pop: Rem ove the top elem entofthe stack Term inology from spring-loaded stack ofplatesin a cafeteria: A dding a plate pushesthose below itdow n in the stack Rem oving a plate popsthose below itup one position.

Upload: vui

Post on 31-Jan-2016

34 views

Category:

Documents


0 download

DESCRIPTION

stack as an ADT. Example use of (LIFO) Stack. Example -- Continued. Designing a Stack Class. Implementing a Stack Class. Implementing Stack Class -- Refined. Implementing Stack Class -- Continued. Implementing Stack Class -- Continued. Implementing Stack Class -- Continued. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: stack as an ADT

stack as an ADT

A stack is an ordered collection of data itemsaccess is possible only at one end ( top of the stack).

Basic operations1. Construct a stack (usually empty)2. Check if stack is empty3. Push: Add an element at the top of the stack

4. Top: Retrieve the top element of the stack 5. Pop: Remove the top element of the stack

Terminology from spring-loaded stack of plates in a cafeteria:

• Adding a plate pushes those below it down in the stack• Removing a plate pops those below it up one position.

Page 2: stack as an ADT

Example use of (LIFO) Stack

BASE-CONVERSION ALGORITHM (See p. 171-2)/* Display the base-2 representation of a base-10 number.

Receive: a positive integer number.Output: the base-two representation of number.

*/1. Create an empty stack to hold the remainders.2. While number > 0:

a. Calculate the remainder from number divided by 2.b. Push remainder onto the stack of remainders.c. Replace number by the integer quotient of number divided by 2.

3. While the stack of remainders is not empty:a. Retrieve and remove the remainder from the top of the stackb. Display remainder.

Page 3: stack as an ADT

Example -- Continued // code that uses stack object stackOfRemainderscout << "Enter positive integer to convert: ";cin >> number;

while (number != 0){remainder = number % 2;stackOfRemainders.push(remainder);number /= 2;

}

cout << "Base-two representation: ";while (!stackOfRemainders.empty() ){remainder = stackOfRemainders.top();stackOfRemainders.pop();cout << remainder;

}

Page 4: stack as an ADT

Designing a Stack Class

identify operations needed to manipulate "real-world" object modeled by class.

operations described independent of class implementation. in a manner independent of any specific representation of object.

Stack operations:• Construction: Initializes an empty stack.• Empty operation: Determines if stack contains any values• Push operation: Modifies a stack by adding a value to top of stack• Top operation: Retrieves the value at the top of the stack• Pop operation: Modifies a stack by removing the top value of the stack

To help with debugging, add early on:

Output: Displays all the elements stored in the stack.

Page 5: stack as an ADT

Implementing a Stack ClassD e f i n e d a t a m e m b e r s : c o n s i d e r s t o r a g e s t r u c t u r e ( s )

A t t e m p t # 1 : U s e a n a r r a y w i t h t h e t o p o f t h e s t a c k a t p o s i t i o n 0 .e . g . , P u s h 7 5 , P u s h 8 9 , P u s h 6 4 , P o p

0 1 2 3 4

7 5 0 1 2 3 4

8 90 1 2 3 4

P u sh 7 5 P u sh 8 9

7 50 1 2 3 4

8 9

P u sh 6 4

7 5

6 4 0 1 2 3 4

8 9P o p

7 5

+ f e a t u r e s : T h i s m o d e l s t h e o p e r a t i o n o f t h e s t a c k o f p l a t e s .– f e a t u r e s : N o t e f f i c i e n t t o s h i f t t h e a r r a y e l e m e n t s u p a n d d o w n i n t h e a r r a y .

Page 6: stack as an ADT

Implementing Stack Class -- Refined

I n s t e a d o f m o d e l i n g t h e s t a c k o f p l a t e s , m o d e l a s t a c k o f b o o k s . K e e p t h e b o t t o m o f s t a c k a t p o s i t i o n 0 M a i n t a i n a " p o i n t e r " m y T o p t o t h e t o p o f t h e s t a c k .

e . g . , P u s h 7 5 , P u s h 8 9 , P u s h 6 4 , P o p

7 58 9

4 3 2 1 0

P u sh 7 5 P u sh 8 9

7 58 9

P u sh 6 4

7 5

6 4

P o p4 3 2 1 0

4 3 2 1 0

4 3 2 1 0

4 3 2 1 0

8 97 5

6 4

myTop myTop

myTop myTop

myTop

m y T o p = – 1 m y T o p = 0 m y T o p = 1 m y T o p = 2 m y T o p = 1

N o t e : N o m o v i n g o f a r r a y e l e m e n t s .

Page 7: stack as an ADT

Implementing Stack Class -- ContinuedBegin the declaration of class by selecting data members:

Provide array data member to hold the stack elements. constant data member to refer to the capacity of the array integer data member to indicate the top of the stack.

Problems: need an array declaration of the formArrayElementType myArray[ARRAYCAPACITY];

What type should be used?Solution (for now): Use the typedef mechanism:

typedef int StackElement;// put this before the class declaration

What about the capacity?const int STACK_CAPACITY = 128;// put this before the class declaration

Page 8: stack as an ADT

Implementing Stack Class -- Continued1. typedef makes StackElement a synonym for int

2. The typedef outside the class makes it accessible throughout the class and in any file that #includes Stack.h without qualification

(Stack::StackElement needed if data member)

3. Want a stack of reals, or characters, or ... ? Change the typedeftypedef double StackElementType;

ortypedef char StackElementType;

or . . .When class library recompiled, array elements will be double or char or .

4. An alternative to using and changing a typedef: a template A Stack class is built whose element type is left unspecified.The element type is passed as a special kind of parameter at compile time.

Page 9: stack as an ADT

Implementing Stack Class -- Continued#ifndef STACK#define STACK

const int STACK_CAPACITY = 128;typedef int StackElement;

class Stack{/***** Function Members *****/public: . . ./***** Data Members *****/private: StackElement myArray[STACK_CAPACITY]; int myTop;}; // end of class declaration. . .#endif

Page 10: stack as an ADT

Implementing Stack Class Methods

/ * - - - C o n s t r u c t o r S i m p l e e n o u g h t o i n l i n e ? Y e s

P r e c o n d i t i o n : A s t a c k h a s b e e n d e c l a r e d . P o s t c o n d i t i o n : S t a c k h a s b e e n c o n s t r u c t e d a s a n e m p t y s t a c k .* /i n l i n e S t a c k : : S t a c k ( ) { m y T o p = - 1 ; }

S t a c k S ; / / w i l l c o n s t r u c t S a s f o l l o w s :

S 0 1 2 3 4 . . .1 2 7m y A r r a y ? ? ? ? ? . . . ?

m y T o p - 1

Page 11: stack as an ADT

Implementing Stack Class Methods

/* --- Is the Stack empty?

const function? (Shouldn't alter data members) Yes

Simple enough to inline? Yes ---* Receive:stack containing function (implicitly)* Returns: true if this Stack empty*/

inline bool Stack::empty() const{ return (myTop == -1); }

Page 12: stack as an ADT

Implementing Stack Class Methods/* --- Add a value to the stack

Simple enough to inline? Probably not ---* Receive: The Stack containing function (implicitly)* A value to be added to a Stack* Pass back: Stack (implicitly)with value added* Output: "Stack full" message if no space for value*/// In Stack.cppvoid Stack::push(const StackElement & value){ if (myTop < STACK_CAPACITY - 1) // stack invariant { ++myTop; myArray[myTop] = value; } else cerr << "*** Stack full:can't add new value ***\n" << "increase STACK_CAPACITY in Stack.h\n";}

Page 13: stack as an ADT

Implementing Stack Class Methods/* --- Display values stored in the stack --- * const function? (Shouldn't alter data members?) Yes

Simple enough to inline? No * Receive: Stack containing function (implicitly) * ostream out * Output: The Stack's contents, from top down */

// in Stack.cppvoid Stack::display(ostream & out) const{ for (int i = myTop; i >= 0; i--) out << myArray[i] << endl;}

Page 14: stack as an ADT

Implementing Stack Class Methods/* --- Return value at top of the stack --- * const function? Yes

Simple enough to inline? Probably not * Receive: Stack containing function (implicitly) * Return: value at the top of nonempty Stack * Output: "Stack empty" message if stack empty */

// in Stack.cpp

StackElement Stack::top() const{ if (myTop >= 0) return (myArray[myTop]); cerr << "*** Stack is empty ***\n";}

Page 15: stack as an ADT

Implementing Stack Class Methods/* --- Remove value at top of the stack --- * const function? No

Simple enough to inline? Probably not * Receive: Stack containing function (implicitly) * Pass back: Stack containing function (implicitly) * with top value (if any) removed * Output: "Stack-empty" message if stack is empty. */

// in Stack.cppvoid Stack::pop(){ if (myTop >= 0) // stack invariant myTop--; else cerr << "** Stack empty:can't remove value *\n";}

Page 16: stack as an ADT

Run-time StackWhen a function begins execution (i.e., is activated),

an activation record (or stack frame) is createdto store the current environment for that function.

Contents of activation record include:

parameters

caller's state information (saved)(e.g., contents of registers, return address)

local variables

temporary storage

Problem: FunctionA can call FunctionB; FunctionB can call FunctionC

When FunctionC finishes, control should return to FunctionBWhen FunctionB finishes, control should return to FunctionA.

The order of returns from function is the reverse of function invocations: LIFO Use a stack to store the activation records

Page 17: stack as an ADT

Run-time StackWhen a function called,

(1) Push a copy of its activation record onto the run-time stack(2) Copy its arguments into the parameter spaces(3) Transfer control to the address of the function's body

The top activation record in the run-time stackis always that of the function currently executing.

When a function terminates,(1) Pop activation record of terminated function

from the run-time stack(2) Use new top activiation record to

restore the environment of the interrupted functionand resume execution of the interrupted function

overhead associated with function calls pushing and popping of the run-time stack avoided by inline functions (call replaced with body of function)

Page 18: stack as an ADT

Reverse Polish Notation RPN?

A notation for arithmetic expressions:operators are written after the operands.

Expressions can be written without using parenthesesDeveloped by Polish logician, Jan Lukasiewics, in 1950's

Infix notation: operators written between the operandsPostfix notation (RPN): operators written after the operandsPrefix notation : operators written before the operands

Examples:INFIX RPN (POSTFIX) PREFIX

A + B A B + + A BA * B + C A B * C + + * A B CA * (B + C) A B C + * * A + B CA–(B –(C – D)) A B C D - - - - A - B - C DA – B – C – D A B - C - D - - - - A B C D

Page 19: stack as an ADT

Evaluating RPN Expressions"By hand": Underlining technique:

1. Scan the expression from left to right to find an operator.2. Locate ("underline") the last two preceding operands

and combine them using this operator.3. Repeat until the end of the expression is reached.

Example:

2 3 4 + 5 6 - - * 2 3 4 + 5 6 - - * 2 7 5 6 - - * 2 7 5 6 - - * 2 7 -1 - * 2 7 -1 - * 2 8 * 2 8 * 16

Page 20: stack as an ADT

Evaluating RPN ExpressionsSTACK ALGORITHMReceive: An RPN expression.Return: A stack whose top element is the value of RPN expression

(unless an error occurred).

1. Initialize an empty stack.2. Repeat the following until the end of the expression is encountered:

a. Get next token (constant, variable, arithmetic operator) in the RPNexpression.

b. If token is an operand, push it onto the stack.If it is an operator, then(i) Pop top two values from the stack.

If stack does not contain two items, error due to a malformed RPNEvaluation terminated

(ii) Apply the operator to these two values.(iii) Push the resulting value back onto the stack.

3. When the end of expression encountered, its value is on top of the stack(and, in fact, must be the only value in the stack).

Page 21: stack as an ADT

Evaluating RPN ExpressionsUnary minus causes problems

Example: 5 3 - - 5 3 - - 5 -3 - 8

5 3 - - 5 3 - - 2 - -2

Use a different symbol: 5 3 ~ -5 3 - ~

Page 22: stack as an ADT

Sample RPN EvaluationExample: 2 3 4 + 5 6 - - *

Push 2Push 3Push 4Read +

Pop 4, Pop 3, 3 + 4 = 7Push 7

Push 5Push 6Read -

Pop 6, Pop 5, 5 - 6 = -1Push -1

Read -Pop -1, Pop 7, 7 - -1 = 8Push 8

Read *Pop 8, Pop 2, 2 * 8 = 16

Page 23: stack as an ADT

Converting Infix to RPN IBy hand: Represent infix expression as an expression tree:

A * B + C

*

+

A B

C

A * (B + C)

*

+A

B C

((A + B) * C) / (D - E)

C

A B

D E

*

+

/

-

Page 24: stack as an ADT

Converting Infix to RPN ITraverse the tree in Left-Right-Parent order to get RPN

Postorder AB+C*DE-/

Traverse tree in Parent-Left-Right order to get Prefix

Preorder /*+ABC-DE

Traverse tree in Left-Parent-Right order to get Infix -- must insert ()'s

inorder ((A+B)*C)/(D-E)

Page 25: stack as an ADT

Converting Infix to RPN IIB y h a n d : " F u l l y p a r e n t h e s i z e - m o v e - e r a s e " m e t h o d :

1 . F u l l y p a r e n t h e s i z e t h e e x p r e s s i o n .2 . R e p l a c e e a c h r i g h t p a r e n t h e s i s b y t h e c o r r e s p o n d i n g o p e r a t o r .3 . E r a s e a l l l e f t p a r e n t h e s e s .

E x a m p l e :

( ( A + B ) * C ) / ( D - E )

( ( ( A B + C * ( D E - /

A B + C * D E - /

( ( ( A + B ) * C ) / ( D - E ) )

Page 26: stack as an ADT

Converting Infix to RPN IIIStack Algorithm1. Initialize an empty stack of operators.2. While no error has occurred and end of infix expression not reached

a. Get next Token in the infix expression.b. If Token is

(i) a left parenthesis: Push it onto the stack.(ii) a right parenthesis:

Pop and display stack elements until a left parenthesis is encountered,but do not display it. (Error if stack empty with no left parenthesis found.)

(iii) an operator:If stack empty or Token has higher priority than top stack element, push Token on stack.

( Left parenthesis in stack has lower priority than operators)Otherwise, pop and display the top stack element; thenrepeat the comparison of Token with new top stack item.

(iv) an operand: Display it.

3. When end of infix expression reached,pop and display stack items until stack is empty.

Page 27: stack as an ADT

Converting Infix to RPN IIIExample: ((A+B)*C)/(D-E)

Push (Push (Display A APush +Display B ABRead )

Pop +, Display +, Pop ( AB+Push *Display C AB+CRead )

Pop *, Display *, Pop ( AB+C* // stack now emptyPush /Push (Display D AB+C*DPush -Display E AB+C*DERead )

Pop -, Display -, Pop ( AB+C*DE-Pop /, Display / AB+C*DE-/