Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.

6
Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware

Transcript of Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.

Page 1: Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.

Stacks

CISC181 Spring 2004

P. T. Conrad

University of Delaware

Page 2: Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.

stacks: push and pop

Page 3: Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.

stack: last in, first out (lifo)

3

•only the thing on top of the stack is accessible

•push: add something on top of the stack

•pop: remove something from the top of the stack (and return it as the result of the pop operation)

initialstack

after:push(3)

11

3

after:push(11)

-2

11

3

after:push(-2)

11

3

after:pop

(returns -2)

7

11

3

after:push(7)

11

3

after:pop

(returns 7)

Page 4: Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.

"a stack" vs. "the stack"

• computer systems use lots of stacks– laser printers use stacks to process PostScript – compilers use stacks to convert C++ into a.out– stacks are used to process HTML code

• "a stack" means "any old stack"• but when we say "the stack",

we mean a specific one: the "run-time stack"– we use it to keep track of function calls– we use it to store local automatic variables

(most variables we've seen so far are local automatic variables)

Page 5: Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.

run-time stackcall a function: push

return from a function: pop

main

sumSquares

squared

i

n

answer

i

y

Page 6: Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.

run-time stack for factorialcall a function: push

return from a function: pop

main

fact

i=4

x=4

fact

i=3

fact

i=2

fact

i=1

...int factorial(int i){ if (i<=1) return 1; else return i * factorial (i – 1);}

int main(void){ int x=4; cout << factorial(x); return 0;}

return 1

return 2 * 1 = 2

return 3 * 2 = 6

return 4 * 6 = 24

cout << 24;