chapter 16 stacks & queues. objective in this chapter we will learn: stacks queues different...

Post on 03-Jan-2016

233 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

chapter 16

Stacks & Queues

Objective

In this chapter we will learn:StacksQueues Different implementations (arrays and linked

list) of both Comparison of implementation

Two Implementations of Stack

As Vector

Store the items contiguously in a vector. As list

Store items noncontiguously in a linked list

Stack – Vector Implementation

template <class Object>class Stack{ { public: Stack( ); bool isEmpty( ) const; const Object & top( ) const; void makeEmpty( ); void pop( ); void push( const Object &

x ); Object topAndPop( ); private: vector<Object> theArray; int topOfStack; };

A stack can be implemented with an vector and an integer that indicates the index of the top element.

//construct the stackTemplate <class Object>Stack<Object>::Stack():the Array(1){

topOfStack = -1;}

//test if the stack is logically emptyTemplate <class Object>Stack<Object>::isEmpty() const{ return topOfStack == -1;}

How stack works

a

b

a a

tos= -1

tos=0

tos=2

pop(b)push(a) push(b)Empty stack

tos=1

The push/pop function (vector-based)template <class Object> void Stack<Object>::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 <class Object> void Stack<Object>::pop() { if( isEmpty()) throw UnderflowException(); topOfStack--; }

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 ).

Queue Back

a

Back

a b

Back

b

Back

Step 1. makeEmpty()

Step 2. enqueue(a)

Step 3. enqueue(b)

b

Back

After dequeue() :

Step 4. dequeue()

Better Idea Keep a Front index. To Dequeue, increment Front. Therefore,

Dequeue takes constant time now.

a b c d

Front Back

b c d

Front Back

Queue

Front

Back

a

Front

Back

a b

Front

Back

b

Front

BackStep 1. makeEmpty()

Step 2. enqueue(a)

Step 3. enqueue(b)

b

Front

Back

after dequeue():

Step 4. dequeue()

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.

Circular Example Both Front and Back wraparound as

needed.

b c d

Front Back

b c d

FrontBack

e f

e fg

Mostly straightforward; maintainFrontBackCurrentSize: 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

Queue – Vector ImplementationTemplate <class Object>

Class Queue{

public:

Queue();

bool isEmpty() const;

const Object & getFront() const;

void makeEmpty();

Object dequeue();

void enqueue (const Ojbect & x);

private:

vector<Object> theArray;

int currentSize;

int front;

int back;

void increment (int & x) const;

void doubleQueue();

template <class Object>

void Queue<Object>::enqueue(const Object & x){

if(currentSize == theArray.size())

doubleQueue();

increment( back);

theArray[back] = x;

currentSize++;

}

template <class Object>

void Queue<Object>::doubleQueue() {

theArray.resize(theArray.size() * 2 + 1);

if(front != 0){

for(int i=0; i<front; i++){

theArray[i+currentSize] = theArray[i];

back += currentSize;

}

}

Queue – Vector Implementation cont.

template <class Object>void Queue<Object>::increment(int &

x) const{x++;if(x == theArray.size())

x = 0;}

template <class Object>

Object Queue<Object>::dequeue() {

if( isEmpty())

throw UnderflowException();

currentSize--;

Object frontItem = theArray[front];

increment(front);

return frontItem;

}

template <class Object>

const Object & Queue<Object>::getFront() const {

if (isEmpty())

throw UnderflowException();

return theArray[front];

}

template <class Object>

void Queue<Object>::makeEmpty(){

currentSize = 0;

front = 0;

back = theArray.size() –1;

}

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.

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

Stack

Each stack item storeselement valuepointer to next element

•Stack Interface and Implementation by Linked listStackLi.h http://www.cs.fiu.edu/~weiss/adspc++2/code/StackLi.hStackLi.cpphttp://www.cs.fiuedu/~weiss/adspc++2/code/StackLi.cpp

•Test Program:TestStackLi.cpphttp://www.cs.fiu.edu/~weiss/adspc++2/code/TestStackLi.cpp

Queue

Same idea, but has front and back

backfront

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.

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.

Access both ends is allowed.

a b

Front

Back

b a

Back

Front

a

Front

Back

Adding b to double queue:

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.

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)

Summary

Stack and Queue implementations are overviewed.

top related