stack resize scale by constant
play

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


  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 i th resize: Total resize cost: 1

  2. Stack summary Linked list implementation: Array implementation: Why use an array based implementation? 2

  3. Queue abstract data type class Queue{ enqueue(1) public : enqueue(2) Queue(); LIT dequeue(); enqueue(3) void enqueue( const LIT & e); dequeue() bool empty() const ; private : dequeue() ... enqueue(4) }; dequeue() enqueue(5) dequeue() dequeue() 3

  4. Queue: Linked list implementation a b c d e NULL class Queue{ LIT Queue<LIT>::dequeue(){ public : assert(!empty()); Queue(); LIT ret = LIT dequeue(); Node * temp = void enqueue( const LIT & e); = ->next; bool empty() const ; delete temp; private : return ret; struct Node{ } LIT data; Node * next; void Queue<LIT>:: ...}; enqueue( const LIT & e){ Node * entry; if (empty()) Node * exit; entry = exit = new Node(e); int size; else }; ->next = new Node(e); = ->next; Runtime: } 4

  5. Queue: Array implementation 0 5 9 size - 1 a b c d entry = 9 exit = 5 class Queue{ LIT Queue<LIT>::dequeue(){ public : assert(!empty()); Queue(); LIT ret = items[exit]; LIT dequeue(); exit = (exit + 1) % size; void enqueue( const LIT & e); return ret; bool empty() const ; } private : LIT * items; void Queue<LIT>:: int entry; enqueue( const LIT & e){ int exit; if (isFull()) resize(); int size; items[entry] = e; bool isFull() const ; entry = (entry + 1) % size; void resize(); } }; Runtime: 5

  6. Queue: Array resize Bad Good entry = 2 exit = 3 entry = 2 exit = 3 A C T A C T A C T T A C exit = 0 entry = 3 entry = 2 exit = 3 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

Recommend


More recommend