stacks l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Stacks PowerPoint Presentation
Download Presentation
Stacks

Loading in 2 Seconds...

play fullscreen
1 / 77

Stacks - PowerPoint PPT Presentation


  • 244 Views
  • Uploaded on

Stacks. Briana B. Morrison Adapted from Alan Eugenio. Topics. Define Stack APIs Applications Create Hex Number Recursion Converting from Infix to Postfix Evaluating Postfix Two stacks Single stack Implementation Array based Linked list based. Stacks.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Stacks' - maylin


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
stacks

Stacks

Briana B. Morrison

Adapted from Alan Eugenio

topics
Topics
  • Define Stack
  • APIs
  • Applications
    • Create Hex Number
    • Recursion
    • Converting from Infix to Postfix
    • Evaluating Postfix
      • Two stacks
      • Single stack
  • Implementation
    • Array based
    • Linked list based

Stacks

stacks3
Stacks
  • A stack is a sequence of items that are accessible at only one end of the sequence.

Stacks

pushing popping a stack
Pushing/Popping a Stack
  • Because a pop removes the item last added to the stack, we say that a stack has LIFO (last-in/first-out) ordering.

Stacks

slide8

CLASS stack

CLASS stack

<stack>

<stack>

Constructor

Operations

stack();

Create an empty stack

bool empty(); const

Check whether the stack is empty. Return true if it is empty and false otherwise.

Stacks

slide9

CLASS stack

<stack>

Operations

void pop();

Remove the item from the top of the stack. Precondition: The stack is not empty. Postcondition: Either the stack is empty or the stack has a new topmost item from a previous push.

void push(const T& item);

Insert the argument item at the top of the stack. Postcondition: The stack has a new item at the top.

Stacks

slide10

CLASS stack

<stack>

Operations

int size() const;

Return the number of items on the stack.

T& top() const;

Return a reference to the value of the item at the top of the stack.

Precondition: The stack is not empty.

const T& top() const;

Constant version of top().

Stacks

slide12

DETERMINE THE OUTPUT FROM THE FOLLOWING:

stack<int> my_stack;

for (int i = 0; i < 10; i++)

my_stack.push (i * i);

while (!my_stack.empty())

{

cout << my_stack.top() << endl;

my_stack.pop();

} // while

Stacks

applications of stacks
Applications of Stacks
  • Direct applications
    • Page-visited history in a Web browser
    • Undo sequence in a text editor
    • Saving local variables when one function calls another, and this one calls another, and so on.
  • Indirect applications
    • Auxiliary data structure for algorithms
    • Component of other data structures

Stacks

slide19

STACK APPLICATION

HOW COMPILERS IMPLEMENT

RECURSION

Stacks

slide21

EACH ACTIVATION RECORD CONTAINS:

1. A VARIABLE THAT CONTAINS THE RETURN ADDRESS

IN THE CALLING METHOD;

2. FOR EACH VALUE FORMAL PARAMETER, A VARIABLE THAT CONTAINS A COPY OF THE ARGUMENT;

3. FOR EACH REFERENCE FORMAL PARAMETER, A

VARIABLE THAT CONTAINS THE ADDRESS OF THE

ARGUMENT;

4. FOR EACH VARIABLE DEFINED IN THE METHOD’S BLOCK, A VARIABLE THAT CONTAINS A COPY OF THAT DEFINED VARIABLE. 

Stacks

slide22

THERE IS A RUN-TIME STACK TO

HANDLE THESE ACTIVATION

RECORDS.

PUSH: WHEN FUNCTION IS CALLED

POP: WHEN EXECUTION OF FUNCTION IS COMPLETED

Stacks

slide23

AN ACTIVATION RECORD IS SIMILAR

TO AN EXECUTION FRAME, EXCEPT

THAT AN ACTIVATION RECORD HAS

VARIABLES ONLY, NO CODE.

Stacks

c run time stack
C++ Run-time Stack

main() { int i = 5; foo(i); }

foo(int j) { int k; k = j+1; bar(k); }

bar(int m) { … }

  • The C++ run-time system keeps track of the chain of active functions with a stack
  • When a function is called, the run-time system pushes on the stack a frame containing
    • Local variables and return value
    • Program counter, keeping track of the statement being executed
  • When a function returns, its frame is popped from the stack and control is passed to the method on top of the stack

bar

PC = 1 m = 6

foo

PC = 3 j = 5

k = 6

main

PC = 2 i = 5

Stacks

slide27

STACK APPLICATION

CONVERTING FROM

INFIX TO POSTFIX

Stacks

slide28

IN INFIX NOTATION, AN OPERATOR IS PLACED BETWEEN ITS OPERANDS.

a + b

c – d + (e * f – g * h) / i

Stacks

slide29

OLD COMPILERS:

INFIX MACHINE LANGUAGE

THIS GETS MESSY BECAUSE OF PARENTHESES.

NEWER COMPILERS:

INFIX POSTFIX MACHINE LANG.

Stacks

slide30

In POSTFIX Notation, An OPERATOR is placed IMMEDIATELY AFTER its OPERANDS.

INFIX POSTFIX

a + b ab+

a + b * c abc*+

a * b + c ab*c+

(a + b) * c ab+c*

Stacks

slide31

PARENTHESES ARE NOT NEEDED,

AND NOT USED, IN POSTFIX.

Stacks

slide32

LET’S CONVERT AN INFIX STRING TO

A POSTFIX STRING. 

  x – y * z

Stacks

slide33

POSTFIX PRESERVES THE ORDER OF

OPERANDS, SO AN OPERAND CAN BE

APPENDED TO POSTFIX AS SOON AS

THAT OPERAND IS ENCOUNTERED IN

INFIX.

Stacks

slide34

INFIX POSTFIX

x – y * z x

Stacks

slide35

INFIX POSTFIX

x – y * z x

THE OPERANDS FOR ‘-’ ARE NOT YET

IN POSTFIX, SO ‘-’ MUST BE

TEMPORARILY SAVED SOMEWHERE. (STACK)

Stacks

slide36

INFIX POSTFIX

x – y * z xy

Stacks

slide37

INFIX POSTFIX

x – y * z xy

THE OPERANDS FOR ‘*’ ARE NOT YET

IN POSTFIX, SO ‘*’ MUST BE

TEMPORARILY SAVED SOMEWHERE,

AND RESTORED BEFORE ‘-’.

Stacks

slide38

INFIX POSTFIX

x – y * z xyz

Stacks

slide39

INFIX POSTFIX

x – y * z xyz* –

Stacks

slide40

Suppose, instead, we started with

x*y-z

After moving ‘x’ to postfix, ‘*’ is temporarily saved, and then ‘y’ is appended to postfix. What happens when ‘-’ is accessed?

INFIX POSTFIX

x * y – z xy

Stacks

slide42

THE TEMPORARY STORAGE FACILITY IS A STACK.

HERE IS THE STRATEGY FOR

MAINTAINING THE STACK:

Stacks

slide45

CONVERT FROM INFIX TO POSTFIX:

INFIX POSTFIX

a + b * c / d - e

Stacks

slide46

INFIX POSTFIX

a + b * c / d – e abc*d/+e –

-

/

*

+

OPERATOR STACK

Stacks

slide48

CONVERT TO POSTFIX:

x * (y + z)

Stacks

slide59

STACK APPLICATION

EVALUATING A

POSTFIX EXPRESSION

Stacks

can be done with 1 stack
Can be done with 1 stack
  • Whenever an operand is encountered, push onto stack
  • Whenever operator is encountered, pop required number of arguments from operand stack and evaluate
  • Push result back onto stack

Stacks

another example

3

5

6

2

3

5

5

2

3

5

2

8

8

8

8

8

4

8

1

4

8

2

1

4

8

3

4

8

1

8

8

Another Example

Expression: 5 3 - 6 + 8 2 / 1 2 + - *

Execute 5 - 3

Execute 2 + 6

Execute

1 + 2

Execute

4 - 3

Execute

8 * 1

Execute 8 / 2

Stacks

self test
Self-Test
  • Write the code to reverse an input string using a stack.

Stacks

stack implementations
Stack Implementations
  • Array based
    • Where is top?
    • How are elements added, removed?
  • Linked List based
    • Where is top?
    • How are elements added, removed?
  • Efficiency of operations

Stacks

array based stack implementation
Array Based Stack Implementation

Where should top be?

12

15

5

2

3

4

[0] array

What are array values?

s.push (20)

s.pop( )

stack

Stacks

array based stack
A simple way of implementing the Stack ADT uses an array

We add elements from left to right

A variable keeps track of the index of the top element

Array-based Stack

Algorithmsize()

returnt +1

Algorithmpop()

ifisEmpty()then

throw EmptyStackException

else

tt 1

returnS[t +1]

S

0

1

2

t

Stacks

array based stack cont

S

0

1

2

t

Array-based Stack (cont.)
  • The array storing the stack elements may become full
  • A push operation will then throw a FullStackException
    • Limitation of the array-based implementation
    • Not intrinsic to the Stack ADT

Algorithmpush(o)

ift=S.length 1then

throw FullStackException

else

tt +1

S[t] o

Stacks

performance and limitations
Performance and Limitations
  • Performance
    • Let n be the number of elements in the stack
    • The space used is O(n)
    • Each operation runs in time O(1)
  • Limitations
    • The maximum size of the stack must be defined a priori , and cannot be changed
    • Trying to push a new element into a full stack causes an implementation-specific exception

Stacks

growable array based stack
Growable Array-based Stack
  • In a push operation, when the array is full, instead of throwing an exception, we can replace the array with a larger one
  • How large should the new array be?
    • incremental strategy: increase the size by a constant c
    • doubling strategy: double the size

Algorithmpush(o)

ift=S.length 1then

A new array of

size …

fori0tot do

A[i]  S[i]

S A

tt +1

S[t] o

Stacks

comparison of the strategies
Comparison of the Strategies
  • We compare the incremental strategy and the doubling strategy by analyzing the total time T(n) needed to perform a series of n push operations
  • We assume that we start with an empty stack represented by an array of size 1
  • We call amortized time of a push operation the average time taken by a push over the series of operations, i.e., T(n)/n

Stacks

doubling strategy analysis

geometric series

2

4

1

1

8

Doubling Strategy Analysis
  • We replace the array k = log2n times
  • The total time T(n) of a series of n push operations is proportional to

n + 1 + 2 + 4 + 8 + …+ 2k=

n+ 2k + 1-1 = 2n -1

  • T(n) is O(n)
  • The amortized time of a push operation is O(1)

Stacks

linked list implementation
Linked List Implementation

s.push (‘F’)

s.pop( )

Stacks

stack with a singly linked list
Stack with a Singly Linked List
  • We can implement a stack with a singly linked list
  • The top element is stored at the first node of the list
  • The space used is O(n) and each operation of the Stack ADT takes O(1) time

nodes

t

elements

Stacks

summary slide 1
Summary Slide 1

§- Stack

- Storage Structure with insert (push) and erase (pop) operations occur at one end, called the top of the stack.

- The last element in is the first element out of the stack, so a stack is a LIFO structure.

Stacks

74

summary slide 2
Summary Slide 2

§- Recursion

- The system maintains a stack of activation records that specify:

1) the function arguments

2) the local variables/objects

3) the return address

- The system pushes an activation record when calling a function and pops it when returning.

Stacks

75

summary slide 3
Summary Slide 3

§- Postfix / RPN Expression Notation

- places the operator after its operands

- easy to evaluate using a single stack to hold operands.

- The rules:

1) Immediately push an operand onto the stack.

2) For a binary operator, pop the stack twice, perform the operation, and push the result onto the stack.

3) At the end a single value remains on the stack. This is the value of the expression.

Stacks

76

summary slide 4
Summary Slide 4

§- Infix notation

- A binary operator appears between its operands.

- More complex than postfix, because it requires the use of operator precedence and parentheses.

- In addition, some operators are left-associative, and a few are right-associative.

Stacks

77