Ch4.Stacks Queues

download Ch4.Stacks Queues

of 43

Transcript of Ch4.Stacks Queues

  • 8/3/2019 Ch4.Stacks Queues

    1/43

    http://parasol.tamu.edu

    Chapter 4:Stacks & Queues

    Nancy Amato

    Parasol Lab, Dept. CSE, Texas A&M University

    Acknowledgement: These slides are adapted from slides provided with Data Structures andAlgorithms in C++, Goodrich, Tamassia and Mount (Wiley 2004)

  • 8/3/2019 Ch4.Stacks Queues

    2/43

    Stacks

    2

  • 8/3/2019 Ch4.Stacks Queues

    3/43

    3

    Outline and Reading

    The Stack ADT (4.2.1)

    Applications of Stacks (4.2.3)

    Array-based implementation (4.2.2)

    Growable array-based stack

  • 8/3/2019 Ch4.Stacks Queues

    4/43

    4

    Abstract Data Types (ADTs)

    An abstract datatype (ADT) is anabstraction of a

    data structure An ADT specifies: Data stored

    Operations on the

    data Error conditionsassociated withoperations

    Example: ADT modeling asimple stock trading system

    The data stored are buy/sell

    orders The operations supported are

    order buy(stock, shares, price)

    order sell(stock, shares, price)

    void cancel(order)

    Error conditions: Buy/sell a nonexistent stock

    Cancel a nonexistent order

  • 8/3/2019 Ch4.Stacks Queues

    5/43

    5

    The Stack ADT (4.2.1)

    The Stack ADT storesarbitrary objects

    Insertions and deletionsfollow the last-in first-out(LIFO) scheme

    Think of a spring-loadedplate dispenser

    Main stack operations:

    push(Object o): insertselement o

    pop(): removes and returnsthe last inserted element

    Auxiliary stackoperations:

    top(): returns the lastinserted element withoutremoving it

    size(): returns the numberof elements stored

    isEmpty(): a Booleanvalue indicating whetherno elements are stored

  • 8/3/2019 Ch4.Stacks Queues

    6/43

    6

    Exceptions

    Attempting theexecution of anoperation of ADT may

    sometimes cause anerror condition, calledan exception

    Exceptions are said to

    be thrown by anoperation that cannotbe executed

    In the Stack ADT,operations pop andtop cannot be

    performed if the stackis empty

    Attempting theexecution of pop or

    top on an empty stackthrows anEmptyStackException

  • 8/3/2019 Ch4.Stacks Queues

    7/43

    7

    Exercise: Stacks

    Describe the output of the following series ofstack operations

    Push(8)

    Push(3)

    Pop()

    Push(2)

    Push(5)

    Pop()

    Pop() Push(9)

    Push(1)

  • 8/3/2019 Ch4.Stacks Queues

    8/43

    8

    Applications of Stacks

    Direct applications Page-visited history in a Web browser

    Undo sequence in a text editor

    Saving local variables when one function callsanother, and this one calls another, and so on.

    Indirect applications Auxiliary data structure for algorithms

    Component of other data structures

  • 8/3/2019 Ch4.Stacks Queues

    9/43

    9

    C++ Run-time Stack

    The C++ run-time system keepstrack of the chain of activefunctions with a stack

    When a function is called, the

    run-time system pushes on thestack a frame containing

    Local variables and return value

    Program counter, keeping track ofthe statement being executed

    When a function returns, itsframe is popped from the stackand control is passed to themethod on top of the stack

    main() {int i;

    i = 5;foo(i);}

    foo(int j) {int k;k = j+1;bar(k);}

    bar(int m) {}

    bar

    PC = 1m = 6

    foo

    PC = 3j = 5

    k = 6

    main

    PC = 2i = 5

  • 8/3/2019 Ch4.Stacks Queues

    10/43

    10

    Array-based Stack

    A simple way ofimplementing theStack ADT uses anarray

    We add elementsfrom left to right

    A variable keepstrack of the index of

    the top element

    S

    0 1 2 t

    Algorithmsize()

    returnt + 1

    Algorithmpop()

    ifisEmpty()thenthrow EmptyStackException

    else

    tt 1

    returnS[t + 1]

  • 8/3/2019 Ch4.Stacks Queues

    11/43

    11

    Array-based Stack (cont.)

    The array storing thestack elements maybecome full

    A push operation will

    then throw aFullStackException

    Limitation of the array-based implementation

    Not intrinsic to the Stack

    ADT

    S

    0 1 2 t

    Algorithmpush(o)

    ift = S.length 1 then

    throw FullStackException

    elsett + 1

    S[t] o

  • 8/3/2019 Ch4.Stacks Queues

    12/43

    12

    Performance and Limitations- array-based implementation of stack ADT

    Performance Letn be the number of elements in the stack

    The space used is O(n)

    Each operation runs in time O(1) Limitations

    The maximum size of the stack must be defined apriori, and cannot be changed

    Trying to push a new element into a full stackcauses an implementation-specific exception

  • 8/3/2019 Ch4.Stacks Queues

    13/43

    Growable Array-based Stack

    In a push operation, whenthe array is full, instead ofthrowing an exception, we

    can replace the array with alarger one

    How large should the newarray be?

    incremental strategy: increasethe size by a constantc

    doubling strategy: double thesize

    Algorithm push(o)

    ift = S.length 1then

    A

    new array ofsize

    fori0totdo

    A[i] S[i]

    S A

    t t + 1

    S[t] o

    13

  • 8/3/2019 Ch4.Stacks Queues

    14/43

    14

    Growable Array-based Stack

    In a push operation, when thearray is full, instead of throwingan exception, we can replacethe array with a larger one

    How large should the new arraybe?

    incremental strategy: increase thesize by a constantc

    doubling strategy: double the size

    Algorithmpush(o)

    ift = S.length 1 then

    Anew array of

    size

    fori

    0tot doA[i]S[i]

    SA

    t t + 1

    S[t] o

  • 8/3/2019 Ch4.Stacks Queues

    15/43

    15

    Comparison of theStrategies

    We compare the incremental strategy and thedoubling strategy by analyzing the total time T(n)needed to perform a series ofn push operations

    We assume that we start with an empty stackrepresented by an array of size 1

    We call amortized timeof a push operation theaverage time taken by a push over the series of

    operations, i.e., T(n)/n

  • 8/3/2019 Ch4.Stacks Queues

    16/43

    16

    Incremental Strategy Analysis

    We replace the arrayk =n/c times

    The total time T(n) of a series ofn push operations isproportional to

    n +c + 2c + 3c + 4c + +kc =

    n +c(1 + 2 + 3 + +k) =

    n +ck(k + 1)/2

    Sincec is a constant, T(n) is O(n +k2),i.e., O(n2)

    The amortized time of a push operation is O(n)

  • 8/3/2019 Ch4.Stacks Queues

    17/43

    17

    Doubling Strategy Analysis

    We replace the arrayk = log2ntimes

    The total time T(n) of a series of

    n push operations is proportionalto

    n + 1 + 2 + 4 + 8 + + 2k=

    n+ 2k + 11 = 2n 1

    T(n) is O(n) The amortized time of a push

    operation is O(1)

    geometric series

    1

    2

    1

    4

    8

  • 8/3/2019 Ch4.Stacks Queues

    18/43

    18

    Stack Interface in C++

    Interfacecorresponding toour Stack ADT

    Requires thedefinition of classEmptyStackException

    Most similar STLconstruct is vector

    template classStack{public:

    int size();bool isEmpty();

    Object& top()throw(EmptyStackException);

    voidpush(Object o);Object pop()

    throw(EmptyStackException);};

  • 8/3/2019 Ch4.Stacks Queues

    19/43

    19

    Array-based Stack in C++

    template classArrayStack {private:

    int capacity; // stack capacity

    Object *S; // stack arrayint top; // top of stack

    public:ArrayStack(int c){

    capacity = c;

    S = new Object[capacity];t = 1;}

    bool isEmpty(){ return(t < 0); }

    Object pop()

    throw(EmptyStackException) {if(isEmpty())throw EmptyStackException

    (Access to empty stack);return S[t--];

    }// (other functions omitted)

  • 8/3/2019 Ch4.Stacks Queues

    20/43

    20

    Singly Linked List(we will formalize List ADT in Ch. 5)

    A singly linked list is aconcrete data structureconsisting of a sequenceof nodes

    Each node stores element

    link to the next node

    next

    elem node

    A B C D

  • 8/3/2019 Ch4.Stacks Queues

    21/43

    4/27/2012 3:06 AMVectors 21

    Stack with a Singly Linked List

    We can implement a stack with a singly linked list

    The top element is stored at the first node of the list

    The space used is O(n) and each operation of theStack ADT takes O(1) time

    tnodes

    elements

    top

  • 8/3/2019 Ch4.Stacks Queues

    22/43

    4/27/2012 3:06 AMVectors 22

    Exercise

    Describe how to implement a stack using a singly-linked list

    Stack operations: push(x), pop( ), size(), isEmpty()

    For each operation, give the running time

  • 8/3/2019 Ch4.Stacks Queues

    23/43

    Stack Summary

    Stack Operation Complexity for Different Implementations

    4/27/2012 3:06 AMVectors 23

    ArrayFixed-Size

    ArrayExpandable (doublingstrategy)

    ListSingly-Linked

    Pop() O(1) O(1) O(1)

    Push(o) O(1) O(n) Worst CaseO(1) Best CaseO(1) Average Case

    O(1)

    Top() O(1) O(1) O(1)

    Size(), isEmpty() O(1) O(1) O(1)

  • 8/3/2019 Ch4.Stacks Queues

    24/43

    Queues

    24

  • 8/3/2019 Ch4.Stacks Queues

    25/43

    25

    Outline and Reading

    The Queue ADT (4.3.1)

    Implementation with a circular array (4.3.2)

    Growable array-based queue

    Linked List ADT

    List-based queue

    Queue interface in C++

  • 8/3/2019 Ch4.Stacks Queues

    26/43

    26

    The Queue ADT (4.3.1)

    The Queue ADT storesarbitrary objects

    Insertions and deletions followthe first-in first-out (FIFO)scheme

    Insertions are at the rear of thequeue and removals are at thefront of the queue

    Main queue operations:

    enqueue(object o): inserts

    element o at the end of thequeue

    dequeue(): removes andreturns the element at the frontof the queue

    Auxiliary queue operations: front(): returns the element at

    the front without removing it

    size(): returns the number ofelements stored

    isEmpty(): returns a Booleanvalue indicating whether noelements are stored

    Exceptions Attempting the execution of

    dequeue or front on an emptyqueue throws anEmptyQueueException

  • 8/3/2019 Ch4.Stacks Queues

    27/43

    27

    Exercise: Queues

    Describe the output of the following series ofqueue operations

    enqueue(8)

    enqueue(3)

    dequeue()

    enqueue(2)

    enqueue(5)

    dequeue()

    dequeue() enqueue(9)

    enqueue(1)

  • 8/3/2019 Ch4.Stacks Queues

    28/43

    28

    Applications of Queues

    Direct applications Waiting lines

    Access to shared resources (e.g., printer)

    Multiprogramming

    Indirect applications Auxiliary data structure for algorithms

    Component of other data structures

  • 8/3/2019 Ch4.Stacks Queues

    29/43

    29

    Array-based Queue

    Use an array of sizeNin a circular fashion

    Two variables keep track of the front and rear

    f index of the front element

    r index immediately past the rear element

    Array locationr is kept empty

    Q

    0 1 2 rf

    normal configuration

    Q

    0 1 2 fr

    wrapped-around configuration

  • 8/3/2019 Ch4.Stacks Queues

    30/43

    30

    Queue Operations

    We use themodulo operator(remainder of

    division)

    Algorithmsize()

    return(N - f + r) mod N

    AlgorithmisEmpty()

    return(f = r)

    Q

    0 1 2 rf

    Q

    0 1 2 fr

  • 8/3/2019 Ch4.Stacks Queues

    31/43

    31

    Queue Operations (cont.)

    Algorithmenqueue(o)

    ifsize() = N 1then

    throw FullQueueException

    else

    Q[r]o

    r(r + 1) mod N

    Operation enqueue throwsan exception if the array isfull

    This exception isimplementation-dependent

    Q

    0 1 2 rf

    Q

    0 1 2 fr

  • 8/3/2019 Ch4.Stacks Queues

    32/43

    32

    Queue Operations (cont.)

    Operation dequeuethrows an exception ifthe queue is empty

    This exception is

    specified in the queueADT

    Algorithmdequeue()

    ifisEmpty() then

    throw EmptyQueueException

    else

    oQ[f]

    f(f + 1) mod N

    return o

    Q

    0 1 2 rf

    Q

    0 1 2 fr

  • 8/3/2019 Ch4.Stacks Queues

    33/43

    Performance and Limitations- array-based implementation of queue ADT

    Performance Letn be the number of elements in the stack

    The space used is O(n)

    Each operation runs in time O(1) Limitations

    The maximum size of the stack must be defined apriori, and cannot be changed

    Trying to push a new element into a full stackcauses an implementation-specific exception

  • 8/3/2019 Ch4.Stacks Queues

    34/43

    34

    Growable Array-based Queue

    In an enqueue operation, when the array isfull, instead of throwing an exception, wecan replace the array with a larger one

    Similar to what we did for an array-basedstack

    The enqueue operation has amortizedrunning time

    O(n) with the incremental strategy O(1) with the doubling strategy

  • 8/3/2019 Ch4.Stacks Queues

    35/43

    4/27/2012 3:06 AMVectors 35

    Exercise

    Describe how to implement a queue using a singly-linked list

    Queue operations: enqueue(x), dequeue(), size(), isEmpty()

    For each operation, give the running time

  • 8/3/2019 Ch4.Stacks Queues

    36/43

    36

    Queue with a Singly Linked List

    We can implement a queue with a singly linked list The front element is stored at the head of the list

    The rear element is stored at the tail of the list

    The space used is O(n) and each operation of the Queue ADTtakes O(1) time

    NOTE: we do not have the limitation of the array basedimplementation on the size of the stack b/c the size of the linkedlist is not fixed, I.e., the queue is NEVER full.

    f

    r

    nodes

    elements

    frontrear

  • 8/3/2019 Ch4.Stacks Queues

    37/43

    37

    Informal C++ Queue Interface

    Informal C++interface for ourQueue ADT

    Requires thedefinition of classEmptyQueueException

    No corresponding

    built-in STL class

    template classQueue{public:

    int size();bool isEmpty();

    Object& front()throw(EmptyQueueException);

    voidenqueue(Object o);Object dequeue()

    throw(EmptyQueueException);};

  • 8/3/2019 Ch4.Stacks Queues

    38/43

    Queue Summary

    Queue Operation Complexity for Different Implementations

    4/27/2012 3:06 AMVectors 38

    ArrayFixed-Size

    ArrayExpandable (doublingstrategy)

    ListSingly-Linked

    dequeue() O(1) O(1) O(1)

    enqueue(o) O(1) O(n) Worst CaseO(1) Best CaseO(1) Average Case

    O(1)

    front() O(1) O(1) O(1)

    Size(), isEmpty() O(1) O(1) O(1)

    The Double Ended Queue ADT

  • 8/3/2019 Ch4.Stacks Queues

    39/43

    39

    The Double-Ended Queue ADT

    (4.5.1)

    The Double-Ended Queue, orDeque, ADT stores arbitraryobjects. (Pronounced deck)

    Richer than stack or queue ADTs.Supports insertions and deletionsat both the front and the end.

    Main deque operations:

    insertFirst(object o): insertselement o at the beginning of thedeque

    insertLast(object o): insertselement o at the end of the deque

    RemoveFirst(): removes andreturns the element at the front ofthe queue

    RemoveLast(): removes andreturns the element at the end ofthe queue

    Auxiliary queue operations:

    first(): returns the element at thefront without removing it

    last(): returns the element at thefront without removing it

    size(): returns the number ofelements stored

    isEmpty(): returns a Booleanvalue indicating whether noelements are stored

    Exceptions

    Attempting the execution ofdequeue or front on an emptyqueue throws anEmptyDequeException

    Doubly Linked List

  • 8/3/2019 Ch4.Stacks Queues

    40/43

    40

    Doubly Linked List(we will formalize List ADTs in Ch. 5)

    A doubly linked list provides a naturalimplementation of the Deque ADT

    Nodes implement Position and store:

    element

    link to the previous node

    link to the next node

    Special trailer and header nodes

    prev next

    elem

    trailerheader nodes/positions

    elements

    node

  • 8/3/2019 Ch4.Stacks Queues

    41/43

    41

    Deque with a Doubly Linked List

    We can implement a deque with a doubly linked list The front element is stored at the first node

    The rear element is stored at the last node

    The space used is O(n) and each operation of the

    Deque ADT takes O(1) time

    lastfirst

    elements

    first

  • 8/3/2019 Ch4.Stacks Queues

    42/43

    Performance and Limitations- doubly linked list implementation of deque ADT

    Performance Letn be the number of elements in the stack

    The space used is O(n)

    Each operation runs in time O(1) Limitations

    NOTE: we do not have the limitation of the arraybased implementation on the size of the stack b/c

    the size of the linked list is not fixed, I.e., thedeque is NEVER full.

  • 8/3/2019 Ch4.Stacks Queues

    43/43

    Deque Summary

    Deque Operation Complexity for Different Implementations

    4/27/2012 3:06 AM

    ArrayFixed-Size

    ArrayExpandable(doubling strategy)

    ListSingly-Linked

    ListDoubly-Linked

    removeFirst(),removeLast()

    O(1) O(1) O(n) forone at listtail, O(1) forother

    O(1)

    insertFirst(o),InsertLast(o)

    O(1) O(n) Worst CaseO(1) Best CaseO(1) Average Case

    O(1) O(1)

    first(), last O(1) O(1) O(1) O(1)

    Size(),isEmpty()

    O(1) O(1) O(1) O(1)