Docsity

Stacks - Data Structures and Algorithm - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Stacks - Data Structures and Algorithm - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Data Structures &

Algorithm Analysis

Stacks

• Stack: what is it?

• ADT

• Applications

• Implementation(s)

Last In First Out

B

A

D

C

B

A

C

B

A

D

C

B

A

E

D

C

B

top A

top

top

top

top

A

Stack Applications

• Real life

– Pile of books

– Plate trays

• More applications related to computer

science

– Program execution stack (read more from your

text)

– Evaluating expressions

Boolean isEmpty(stack) ::= if (stack == CreateS(max_stack_size)) return TRUE else return FALSE Element pop(stack) ::= if (IsEmpty(stack)) return else remove and return the item on the top of the stack.

Stack ADT (cont’d)

Array-based Stack Implementation

• Allocate an array of some size (pre-defined)

– Maximum N elements in stack

• Bottom stack element stored at element 0

• last index in the array is the top

• Increment top when one element is pushed,

decrement after pop

void push(int top, element item) { / add an item to the global stack / if (top >= MAX_STACK_SIZE-1) { stack_full( ); return; } stack[++*top] = item; }

Push

element pop(int top) { / return the top element from the stack / if (top == -1) return stack_empty( ); /* returns and error key / return stack[(top)--]; }

Pop

element pop(pnode top) { /* delete an element from the stack */ pnode temp = top; element item; if (IS_EMPTY(temp)) { fprintf(stderr, “The stack is empty\n”); exit(1); } item = temp->item; top = temp->next; free(temp); return item; }

Pop

Algorithm Analysis

• push O(?)

• pop O(?)

• isEmpty O(?)

• isFull O(?)

• What if top is stored at the beginning of the

array?

The Towers of Hanoi

A Stack-based Application

  • GIVEN: three poles
  • a set of discs on the first pole, discs of different sizes, the smallest discs at the top
  • GOAL: move all the discs from the left pole to the right one.
  • CONDITIONS: only one disc may be moved at a time.
  • A disc can be placed either on an empty pole or on top of a larger disc.

Towers of Hanoi

Towers of Hanoi

Towers of Hanoi