1 / 10

Stacks

A comprehensive guide on implementing stacks using a 1D array, including basic operations like IsEmpty, IsFull, Top, Push, and Pop. Also covers dynamic array doubling for efficient stack resizing.

cbono
Download Presentation

Stacks

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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. a b c d e 0 1 2 3 4 5 6 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

  4. a b c d e 0 1 2 3 4 5 6 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

  5. top a b c d e 0 1 2 3 4 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; }

  6. top a b c d e 0 1 2 3 4 Pop elementpop() { if (top == -1) return StackEmpty(); return stack[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 2k • Number of pushes is at least 2k-1+ 1 • Total time spent on array doubling is S1<=i=k2i • This is O(2k) • So, although the time for an individual push is O(capacity), the time for all n pushes remains O(n)!

More Related