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

25
chapter 16 Stacks & Queues

Upload: edwin-nelson

Post on 03-Jan-2016

231 views

Category:

Documents


0 download

TRANSCRIPT

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

chapter 16

Stacks & Queues

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

Objective

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

list) of both Comparison of implementation

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

Two Implementations of Stack

As Vector

Store the items contiguously in a vector. As list

Store items noncontiguously in a linked list

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

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;}

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

How stack works

a

b

a a

tos= -1

tos=0

tos=2

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

tos=1

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

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--; }

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

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

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

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

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

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

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

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

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

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.

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

Circular Example Both Front and Back wraparound as

needed.

b c d

Front Back

b c d

FrontBack

e f

e fg

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

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

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

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;

}

}

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

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;

}

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

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.

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

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

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

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

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

Queue

Same idea, but has front and back

backfront

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

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.

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

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.

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

Access both ends is allowed.

a b

Front

Back

b a

Back

Front

a

Front

Back

Adding b to double queue:

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

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.

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

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)

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

Summary

Stack and Queue implementations are overviewed.