- 240 Views
- Uploaded on

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

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

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

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

<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

<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

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

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

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

HANDLE THESE ACTIVATION

RECORDS.

PUSH: WHEN FUNCTION IS CALLED

POP: WHEN EXECUTION OF FUNCTION IS COMPLETED

Stacks

AN ACTIVATION RECORD IS SIMILAR

TO AN EXECUTION FRAME, EXCEPT

THAT AN ACTIVATION RECORD HAS

VARIABLES ONLY, NO CODE.

Stacks

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

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

a + b

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

Stacks

INFIX MACHINE LANGUAGE

THIS GETS MESSY BECAUSE OF PARENTHESES.

NEWER COMPILERS:

INFIX POSTFIX MACHINE LANG.

Stacks

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

POSTFIX PRESERVES THE ORDER OF

OPERANDS, SO AN OPERAND CAN BE

APPENDED TO POSTFIX AS SOON AS

THAT OPERAND IS ENCOUNTERED IN

INFIX.

Stacks

x – y * z x

THE OPERANDS FOR ‘-’ ARE NOT YET

IN POSTFIX, SO ‘-’ MUST BE

TEMPORARILY SAVED SOMEWHERE. (STACK)

Stacks

x – y * z xy

THE OPERANDS FOR ‘*’ ARE NOT YET

IN POSTFIX, SO ‘*’ MUST BE

TEMPORARILY SAVED SOMEWHERE,

AND RESTORED BEFORE ‘-’.

Stacks

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

Stacks

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

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 ExampleExpression: 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

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

Where should top be?

12

15

5

2

3

4

[0] array

What are array values?

s.push (20)

s.pop( )

stack

Stacks

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 StackAlgorithmsize()

returnt +1

Algorithmpop()

ifisEmpty()then

throw EmptyStackException

else

tt 1

returnS[t +1]

…

S

0

1

2

t

Stacks

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

tt +1

S[t] o

Stacks

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

- 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 …

fori0tot do

A[i] S[i]

S A

tt +1

S[t] o

Stacks

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

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

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

§- 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

§- 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

§- 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

§- 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

Download Presentation

Connecting to Server..