Stack: Resize scale by constant Original size c then increase by c - - PowerPoint PPT Presentation

stack resize scale by constant
SMART_READER_LITE
LIVE PREVIEW

Stack: Resize scale by constant Original size c then increase by c - - PowerPoint PPT Presentation

Stack: Resize scale by constant Original size c then increase by c when full Run time to push n items into an empty stack? Number of resizes: Cost of i th resize: Total resize cost: 1 Stack summary Linked list implementation: Array


slide-1
SLIDE 1

Stack: Resize scale by constant

Original size c then increase by ×c when full Run time to push n items into an empty stack? Number of resizes: Cost of ith resize: Total resize cost:

1

slide-2
SLIDE 2

Stack summary

Linked list implementation: Array implementation: Why use an array based implementation?

2

slide-3
SLIDE 3

Queue abstract data type

class Queue{ public: Queue(); LIT dequeue(); void enqueue(const LIT & e); bool empty() const; private: ... };

enqueue(1) enqueue(2) enqueue(3) dequeue() dequeue() enqueue(4) dequeue() enqueue(5) dequeue() dequeue()

3

slide-4
SLIDE 4

Queue: Linked list implementation

NULL e d c b a

class Queue{ public: Queue(); LIT dequeue(); void enqueue(const LIT & e); bool empty() const; private: struct Node{ LIT data; Node * next; ...}; Node * entry; Node * exit; int size; };

Runtime:

LIT Queue<LIT>::dequeue(){ assert(!empty()); LIT ret = Node * temp = =

  • >next;

delete temp; return ret; } void Queue<LIT>:: enqueue(const LIT & e){ if (empty()) entry = exit = new Node(e); else

  • >next = new Node(e);

=

  • >next;

} 4

slide-5
SLIDE 5

Queue: Array implementation

a b c d 5 size - 1 9 exit = 5 entry = 9 class Queue{ public: Queue(); LIT dequeue(); void enqueue(const LIT & e); bool empty() const; private: LIT * items; int entry; int exit; int size; bool isFull() const; void resize(); };

Runtime:

LIT Queue<LIT>::dequeue(){ assert(!empty()); LIT ret = items[exit]; exit = (exit + 1) % size; return ret; } void Queue<LIT>:: enqueue(const LIT & e){ if (isFull()) resize(); items[entry] = e; entry = (entry + 1) % size; } 5

slide-6
SLIDE 6

Queue: Array resize

A C T exit = 3 entry = 2 T A C exit = 0 entry = 3 A C T A C T exit = 3 entry = 2 exit = 3 entry = 2

Bad Good

void Queue<LIT>::resize(){ assert(isFull()); LIT * temp = items; items = new LIT[2 * size]; for (int i=0; i < size; i++){ items[i] = temp[(exit + i) % size]; } delete temp; exit = 0; entry = size - 1; // Assumes queue was full when resize called size *= 2; } 6