Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 16 Stacks & Queues. Objective In this chapter we will learn:  Stacks  Queues  Different implementations (arrays and linked list) of both 

Similar presentations


Presentation on theme: "Chapter 16 Stacks & Queues. Objective In this chapter we will learn:  Stacks  Queues  Different implementations (arrays and linked list) of both "— Presentation transcript:

1 chapter 16 Stacks & Queues

2 Objective In this chapter we will learn:  Stacks  Queues  Different implementations (arrays and linked list) of both  Comparison of implementation

3 Two Implementations of Stack As Vector Store the items contiguously in a vector. As list Store items noncontiguously in a linked list

4 Stack – Vector Implementation template class Stack{ { public: Stack( ); bool isEmpty( ) const; const Object & top( ) const; void makeEmpty( ); void pop( ); void push( const Object & x ); Object topAndPop( ); private: vector theArray; int topOfStack; }; A stack can be implemented with an vector and an integer that indicates the index of the top element. //construct the stack Template Stack ::Stack():the Array(1){ topOfStack = -1; } //test if the stack is logically empty Template Stack ::isEmpty() const{ return topOfStack == -1; }

5 How stack works a b aa tos= -1 tos=0 tos=2 pop(b)push(a)push(b)Empty stack tos=1

6 The push/pop function (vector-based) template void Stack ::push( const Object & x ) { if( topOfStack == theArray.size( ) - 1 ) theArray.resize( theArray.size( ) * 2 + 1 ); theArray[ ++topOfStack ] = x; } // If there is no vector doubling, push takes constant time, otherwise it // takes O(N) time. But it does not happen often. template void Stack ::pop() { if( isEmpty()) throw UnderflowException(); topOfStack--; }

7 Queues: Simple Idea Store items in an vector with front item at index zero and back item at index Back. Enqueue is easy: increment Back. Dequeue is inefficient: all elements have to be shifted. (If use only one index) Result: Dequeue will be O( N ).

8 Queue Back a ab b Step 1. makeEmpty() Step 2. enqueue(a) Step 3. enqueue(b) b Back After dequeue() : Step 4. dequeue()

9 Better Idea Keep a Front index. To Dequeue, increment Front. Therefore, Dequeue takes constant time now. abcd FrontBack bcd FrontBack

10 Queue Front Back a Front Back ab Front Back b Front BackStep 1. makeEmpty() Step 2. enqueue(a) Step 3. enqueue(b) b Front Back after dequeue(): Step 4. dequeue()

11 Circular Implementation Previous implementation is O( 1 ) per operation. However, after vector.size() times enqueues, we are full, even if queue is logically nearly empty. Solution: use wraparound to reuse the cells at the start of the vector. To increment, add one, but if that goes past end, reset to zero.

12 Circular Example Both Front and Back wraparound as needed. bcd FrontBack bcd FrontBack ef efg

13 Mostly straightforward; maintain  Front  Back  CurrentSize: Current number of items in queue Only tricky part is vector doubling because the queue items are not necessarily stored in an array starting at location 0, and the contiguity of wraparound must be maintained. QUEUE--Vector Implementation

14 Queue – Vector Implementation Template Class Queue{ public: Queue(); bool isEmpty() const; const Object & getFront() const; void makeEmpty(); Object dequeue(); void enqueue (const Ojbect & x); private: vector theArray; int currentSize; int front; int back; void increment (int & x) const; void doubleQueue(); template void Queue ::enqueue(const Object & x){ if(currentSize == theArray.size()) doubleQueue(); increment( back); theArray[back] = x; currentSize++; } template void Queue ::doubleQueue() { theArray.resize(theArray.size() * 2 + 1); if(front != 0){ for(int i=0; i<front; i++){ theArray[i+currentSize] = theArray[i]; back += currentSize; }

15 Queue – Vector Implementation cont. template void Queue ::increment(int & x) const{ x++; if(x == theArray.size()) x = 0; } template Object Queue ::dequeue() { if( isEmpty()) throw UnderflowException(); currentSize--; Object frontItem = theArray[front]; increment(front); return frontItem; } template const Object & Queue ::getFront() const { if (isEmpty()) throw UnderflowException(); return theArray[front]; } template void Queue ::makeEmpty(){ currentSize = 0; front = 0; back = theArray.size() –1; }

16 Linked List Implementation Advantage of the linked list is that excess memory is only one pointer per item. In contrast, a contiguous vector implementation uses excess space.

17 Stack The stack class can be implemented as a linked list in which the top of the stack is represented by the first item in the list. topOfStack

18 Stack Each stack item stores  element value  pointer to next element Stack Interface and Implementation by Linked list StackLi.h http://www.cs.fiu.edu/~weiss/adspc++2/code/StackLi.h StackLi.cpp http://www.cs.fiuedu/~weiss/adspc++2/code/StackLi.cpp Test Program: TestStackLi.cpp http://www.cs.fiu.edu/~weiss/adspc++2/code/TestStackLi.cpp

19 Queue Same idea, but has front and back back front

20 Comparison of the two methods Both of them run in constant time per operation. The vector version is likely to be faster. But it has two drawbacks:  The wraparound is a little confusing;  It might waste more space.

21 Deque A deque is a double-ended queue. A deque is a kind of sequence that, like a vector, supports random access iterators. In addition, it supports constant time insert and erase operations at the beginning or the end; insert and erase in the middle take linear time. That is, a deque is especially optimized for pushing and popping elements at the beginning and end. As with vectors, storage management is handled automatically.

22 Access both ends is allowed. ab Front Back ba Front a Back Adding b to double queue:

23 Common errors (Page 561) Do not delete the top node directly before adjusting the top of the stack pointer Be aware of memory leaks Access is constant time in both of these implementations.

24 In class exercises Draw the stack and queue data structures for each step in the following add(1), add(2), remove, add(3), add(4), remove, remove, add(5)

25 Summary Stack and Queue implementations are overviewed.


Download ppt "Chapter 16 Stacks & Queues. Objective In this chapter we will learn:  Stacks  Queues  Different implementations (arrays and linked list) of both "

Similar presentations


Ads by Google