data structures - 04. stacks

33
Universidade Federal da Paraíba Centro de Informática Stacks Lecture 6 1107186 – Estrutura de Dados – Turma 02 Prof. Christian Azambuja Pagot CI / UFPB

Upload: emerson-ferreira

Post on 20-Jun-2015

212 views

Category:

Education


0 download

DESCRIPTION

Slide da cadeira de Estrutura de Dados, ministrado pelo Prof. Dr. Christian Pagot, na Universidade Federal da Paraíba.

TRANSCRIPT

Page 1: Data Structures - 04. Stacks

Universidade Federal da ParaíbaCentro de Informática

StacksLecture 6

1107186 – Estrutura de Dados – Turma 02

Prof. Christian Azambuja PagotCI / UFPB

Page 2: Data Structures - 04. Stacks

2Universidade Federal da ParaíbaCentro de Informática

What is a Stack?

Gene Daniels, 1972.

Page 3: Data Structures - 04. Stacks

3Universidade Federal da ParaíbaCentro de Informática

What is a Stack?

● A stack is an abstract data type where elements can be inserted (pushed) and removed (popped) according to the following policies:– Push inserts a new item into the top of the stack.

– Pop removes the item at the top of the stack (except when the stack is empty).

– The above insert/remove policy is also called LIFO (Last In-First Out).

Page 4: Data Structures - 04. Stacks

4Universidade Federal da ParaíbaCentro de Informática

What is a stack?

● Example:

Top 0 5

1 3

0 5

Top

4 7

3 1

2 9

1 3

0 5

Top

3 1

2 9

1 3

0 5

Top

1) push(5) 2) push(3) 3) push(9)4) push(1)5) push(7)

6) pop()

Page 5: Data Structures - 04. Stacks

5Universidade Federal da ParaíbaCentro de Informática

An Useful Operation

● Often we want just to check the value of the topmost item on the stack. One possible approach to that would be:

● An easier way would be to have a function that returns the value at the top without actually popping the value:

x = pop()push(x)

x = top()

Page 6: Data Structures - 04. Stacks

6Universidade Federal da ParaíbaCentro de Informática

Stacks in Practice

● Two example applications:– Parenthesis matching.

– Reverse Polish Notation (RPN)

Page 7: Data Structures - 04. Stacks

7Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● An example arithmetic expression:

● We must check if the parenthesis are correctly grouped:– # of left parenthesis = # of right parenthesis.

– All right parenthesis are preceded by a corresponding left parenthesis.

((a+b)×(c+d)×e)−( f +g )

Page 8: Data Structures - 04. Stacks

8Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● If each left parenthesis counts 1, and each right parenthesis counts -1, the overall sum must be 0 (zero).

● At any position in the expression, the partial sum must not be negative!

How to keep track of the appropriate counting and

ordering?Guess what!

Page 9: Data Structures - 04. Stacks

9Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Each time a left parenthesis is found, it is pushed into the stack.

● Each time a right parenthesis is found, one item is popped from the stack.

● At the end, if the expression is correct, the stack must be empty.

Page 10: Data Structures - 04. Stacks

10Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Example:

((a+b)×(c+d)×e)−( f +g )

0 (

Push(')')

Page 11: Data Structures - 04. Stacks

11Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Example:

((a+b)×(c+d)×e)−( f +g )

1 (

0 (

Push(')')

Page 12: Data Structures - 04. Stacks

12Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Example:

((a+b)×(c+d)×e)−( f +g )

0 (

Pop()

Page 13: Data Structures - 04. Stacks

13Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Example:

1 (

0 (

((a+b)×(c+d)×e)−( f +g )

Push(')')

Page 14: Data Structures - 04. Stacks

14Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Example:

((a+b)×(c+d)×e)−( f +g )

0 (

Pop()

Page 15: Data Structures - 04. Stacks

15Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Example:

((a+b)×(c+d)×e)−( f +g )

Pop()

Page 16: Data Structures - 04. Stacks

16Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Example:

((a+b)×(c+d)×e)−( f +g )

0 (

Push(')')

Page 17: Data Structures - 04. Stacks

17Universidade Federal da ParaíbaCentro de Informática

Parenthesis Matching

● Example:

((a+b)×(c+d)×e)−( f +g )

Pop() Results:

● Stack is empty. ● No underflows during process.

Conclusion:Valid expression!

Page 18: Data Structures - 04. Stacks

18Universidade Federal da ParaíbaCentro de Informática

Mathematical Notation

● One aspect of the mathematical notation is related to the position of the operator relative to its operands in an expression.

● There are three possibilities:– Infix (most common): 5 + 8

– Prefix: + 5 8

– Postfix: 5 8 +

Page 19: Data Structures - 04. Stacks

19Universidade Federal da ParaíbaCentro de Informática

(a+b)×(c+d )

ab+cd+×

● RPN is a postfix, parenthesis free, mathematical notation where the operator follows their operands.

● Example:– Usual arith. expression:

– RPN version:

Reverse Polish Notation (RPN)

Page 20: Data Structures - 04. Stacks

20Universidade Federal da ParaíbaCentro de Informática

Evaluating an Expression in RPN

● OBS: Each operator refers to the two previous operands.

● Algorithm: for each symbol in expression  if (symbol == operand)    stack.push(symbol);  else     if (symbol == operator)      op1 = stack.pop();      op2 = stack.pop();      result = eval(op1 operator op2);      stack.push(result);    end if  end ifend for At the end, the stack will

contain the final result!

Page 21: Data Structures - 04. Stacks

21Universidade Federal da ParaíbaCentro de Informática

Evaluating an Expression in RPN

● Example:

for each symbol in expression  if (symbol == operand)    stack.push(symbol);  else     if (symbol == operator)      op1 = stack.pop();      op2 = stack.pop();      result = op1 operator op2;      stack.push(result);    end if  end ifend for

(5+3)×(5+8)Usual not.:

53+5 8+×RPN not.:

0 5

curr. step

Page 22: Data Structures - 04. Stacks

22Universidade Federal da ParaíbaCentro de Informática

Evaluating an Expression in RPN

● Example:

for each symbol in expression  if (symbol == operand)    stack.push(symbol);  else     if (symbol == operator)      op1 = stack.pop();      op2 = stack.pop();      result = op1 operator op2;      stack.push(result);    end if  end ifend for

(5+3)×(5+8)Usual not.:

53+5 8+×RPN not.:

1 3

0 50 5

curr. stepprev. step

Page 23: Data Structures - 04. Stacks

23Universidade Federal da ParaíbaCentro de Informática

Evaluating an Expression in RPN

● Example:

for each symbol in expression  if (symbol == operand)    stack.push(symbol);  else     if (symbol == operator)      op1 = stack.pop();      op2 = stack.pop();      result = op1 operator op2;      stack.push(result);    end if  end ifend for

(5+3)×(5+8)Usual not.:

53+5 8+×RPN not.:

0 8

1 3

0 5

curr. stepprev. step

Page 24: Data Structures - 04. Stacks

24Universidade Federal da ParaíbaCentro de Informática

Evaluating an Expression in RPN

● Example:

for each symbol in expression  if (symbol == operand)    stack.push(symbol);  else     if (symbol == operator)      op1 = stack.pop();      op2 = stack.pop();      result = op1 operator op2;      stack.push(result);    end if  end ifend for

(5+3)×(5+8)Usual not.:

53+5 8+×RPN not.:

1 5

0 80 8

curr. stepprev. step

Page 25: Data Structures - 04. Stacks

25Universidade Federal da ParaíbaCentro de Informática

Evaluating an Expression in RPN

● Example:

for each symbol in expression  if (symbol == operand)    stack.push(symbol);  else     if (symbol == operator)      op1 = stack.pop();      op2 = stack.pop();      result = op1 operator op2;      stack.push(result);    end if  end ifend for

(5+3)×(5+8)Usual not.:

53+5 8+×RPN not.:

2 8

1 5

0 8

1 5

0 8

curr. stepprev. step

Page 26: Data Structures - 04. Stacks

26Universidade Federal da ParaíbaCentro de Informática

Evaluating an Expression in RPN

● Example:

for each symbol in expression  if (symbol == operand)    stack.push(symbol);  else     if (symbol == operator)      op1 = stack.pop();      op2 = stack.pop();      result = op1 operator op2;      stack.push(result);    end if  end ifend for

(5+3)×(5+8)Usual not.:

53+5 8+×RPN not.:

1 13

0 8

2 8

1 5

0 8

curr. stepprev. step

Page 27: Data Structures - 04. Stacks

27Universidade Federal da ParaíbaCentro de Informática

Evaluating an Expression in RPN

● Example:

for each symbol in expression  if (symbol == operand)    stack.push(symbol);  else     if (symbol == operator)      op1 = stack.pop();      op2 = stack.pop();      result = op1 operator op2;      stack.push(result);    end if  end ifend for

(5+3)×(5+8)Usual not.:

53+5 8+×RPN not.:

0 104

1 13

0 8

curr. stepprev. step

Page 28: Data Structures - 04. Stacks

28Universidade Federal da ParaíbaCentro de Informática

Stack Implementation in C

● A stack is a ordered list of values. ● This approach implements the stack as an

array.– There is no need to allocate space for each new

item :)

– We don't have to worry about deallocating space :)

– Space that is not used is wasted :(

– The stack will be limited in size :(

Page 29: Data Structures - 04. Stacks

29Universidade Federal da ParaíbaCentro de Informática

Stack Implementation in C

● A struct will hold the array and the top indicator:

#define STACK_MAX_SIZE 100

struct Stack{char v[STACK_MAX_SIZE];int top;

};

... 

struct Stack s;

C code excerpt:

Page 30: Data Structures - 04. Stacks

30Universidade Federal da ParaíbaCentro de Informática

Stack Implementation in C

● Push operation:

void Push(struct Stack* s, char c){

if (s­>top < (STACK_MAX_SIZE­1)){

s­>top++;s­>v[s­>top] = c;

}else{

printf("Stack overflow!\n");exit(1);

}};

C code excerpt:

Page 31: Data Structures - 04. Stacks

31Universidade Federal da ParaíbaCentro de Informática

Stack Implementation in C

● Pop operation:

char Pop(struct Stack* s){

if (s­>top >= 0){

char tmp = s­>v[s­>top];s­>top­­;return tmp;

}else{

printf("Stack underflow!\n");exit(1);

}};

C code excerpt:

Page 32: Data Structures - 04. Stacks

32Universidade Federal da ParaíbaCentro de Informática

Stack Implementation in C

● Use example:

int main(void){

struct Stack s = {.top = ­1}; // or s.top = ­1

Push(&s, 'U');Push(&s, 'F');Push(&s, 'P');Push(&s, 'B');

Pop(&s);Pop(&s);

return 0;}

C code excerpt:

Stack creation and initialization.

Pointers as arguments:we need to change

the Stack state!

If not properly initialized, the stack may not work!

Page 33: Data Structures - 04. Stacks

33Universidade Federal da ParaíbaCentro de Informática

Discussion

● Considering the presented implementation:– Initialization is completely manual and prone to errors.

● How to automate it?

– Theoretically, stacks have no upper limits (one should be able to keep 'pushing' infinitely!).

● How we could improve our implementation with respect to the maximum size limit?

– We may want to 'stack' anything (numbers, chars, etc.).● Do we have to implement one different stack (with push(), pop())

for each data type?

Think about it !!!