Download presentation

Presentation is loading. Please wait.

Published byRandell Knight Modified over 2 years ago

1
Stacks Standard operations: IsEmpty … return true iff stack is empty IsFull … return true iff stack has no remaining capacity Top … return top element of stack Push … add an element to the top of the stack Pop … delete the top element of the stack

2
Stacks Use a 1D array to represent a stack. Stack elements are stored in stack[0] through stack[top].

3
Stacks stack top is at element e IsEmpty() => check whether top >= 0 O(1) time IsFull() => check whether top == capacity – 1 O(1) time Top() => If not empty return stack[top] O(1) time 0123456 abcde

4
Derive From arrayList Push(theElement) => if full then either error or increase capacity and then add at stack[top+1] Suppose we increase capacity when full O(capacity) time when full; otherwise O(1) Pop() => if not empty, delete from stack[top] O(1) time 0123456 abcde

5
Push void push(element item) {/* add an item to the global stack */ if (top >= MAX_STACK_SIZE - 1) StackFull(); /* add at stack top */ stack[++top] = item; } 01234 abcde top

6
Pop element pop() { if (top == -1) return StackEmpty(); return stack[top--]; } 01234 abcde top

7
StackFull() void StackFull() { fprintf(stderr, “Stack is full, cannot add element.”); exit(EXIT_FAILURE); }

8
StackFull()/Dynamic Array Use a variable called capacity in place of MAX_STACK_SIZE Initialize this variable to (say) 1 When stack is full, double the capacity using REALLOC This is called array doubling

9
StackFull()/Dynamic Array void StackFull() { REALLOC(stack, 2*capacity*sizeof(*stack); capacity *= 2; }

10
Complexity Of Array Doubling Let final value of capacity be 2 k Number of pushes is at least 2 k-1 + 1 Total time spent on array doubling is i=k 2 i This is O(2 k ) So, although the time for an individual push is O(capacity), the time for all n pushes remains O(n)!

Similar presentations

OK

Stacks Chapter 8. Objectives In this chapter, you will: Learn about stacks Examine various stack operations Learn how to implement a stack as an array.

Stacks Chapter 8. Objectives In this chapter, you will: Learn about stacks Examine various stack operations Learn how to implement a stack as an array.

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Ppt online exam form Animated ppt on magnetism game Download ppt on oxidation and reduction examples Ppt on front office department Topics for ppt on environmental management Ppt on statistics and probability formulas Ppt on our mother earth Ppt on different types of dance forms of bangladesh Ppt on clinical data management Ppt on network switches