Ch4.Stacks Queues.handouts

download Ch4.Stacks Queues.handouts

of 22

Transcript of Ch4.Stacks Queues.handouts

  • 8/3/2019 Ch4.Stacks Queues.handouts

    1/22

    1/31/11

    1

    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 and

    Algorithms in C++, Goodrich, Tamassia and Mount (Wiley 2004)

    Stacks

    2

  • 8/3/2019 Ch4.Stacks Queues.handouts

    2/22

    1/31/11

    2

    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

    4

    Abstract Data Types (ADTs)

    An abstract datatype (ADT) is anabstraction of adata structure

    An ADT specifies:Data storedOperations on the

    data

    Error conditionsassociated withoperations

    Example: ADT modeling asimple stock trading system

    The data stored are buy/sellorders

    The operations supported are orderbuy(stock, shares, price) ordersell(stock, shares, price) void cancel(order)

    Error conditions: Buy/sell a nonexistent stock Cancel a nonexistent order

  • 8/3/2019 Ch4.Stacks Queues.handouts

    3/22

    1/31/11

    3

    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): inserts

    element o pop(): removes and returns

    the 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

    6

    Exceptions

    Attempting theexecution of anoperation of ADT maysometimes cause anerror condition, calledan exception

    Exceptions are said tobe thrown by anoperation that cannotbe executed

    In the Stack ADT,operations pop andtop cannot beperformed if the stackis empty

    Attempting theexecution ofpop or

    top on an empty stackthrows anEmptyStackException

  • 8/3/2019 Ch4.Stacks Queues.handouts

    4/22

    1/31/11

    4

    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

    Applications of Stacks

    Direct applicationsPage-visited history in a Web browserUndo sequence in a text editorSaving local variables when one function calls

    another, and this one calls another, and so on.

    Indirect applicationsAuxiliary data structure for algorithmsComponent of other data structures

  • 8/3/2019 Ch4.Stacks Queues.handouts

    5/22

    1/31/11

    5

    9

    C++ Run-time Stack

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

    When a function is called, therun-time system pushes on thestack a frame containing

    Local variables and return value Program counter, keeping track of

    the 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

    mainPC = 2i = 5

    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()then"" "throw EmptyStackException""else "" "tt - 1"" "returnS[t + 1]"

  • 8/3/2019 Ch4.Stacks Queues.handouts

    6/22

    1/31/11

    6

    11

    Array-based Stack (cont.)

    The array storing thestack elements maybecome full

    A push operation willthen throw aFullStackException

    Limitation of the array-based implementation

    Not intrinsic to the StackADT

    S

    0 1 2 t

    Algorithmpush(o)""ift = S.length - 1 then"" "throw FullStackException""else "" "tt + 1"" "S[t] o"

    12

    Performance and Limitations- array-based implementation of stack ADT

    PerformanceLet n be the number of elements in the stackThe space used is O(n)Each operation runs in time O(1)

    LimitationsThe 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.handouts

    7/22

    1/31/11

    7

    Growable Array-based Stack

    In a push operation, whenthe array is full, instead ofthrowing an exception, wecan replace the array with alarger one

    How large should the newarray be?

    incremental strategy: increasethe size by a constant c

    doubling strategy: double thesize

    Algorithmpush(o)""ift = S.length - 1then"" "A new array of"" " " " "size "" "fori0totdo"" " "A[i] S[i]"" " " S A""t t + 1""S[t] o"

    13

    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 constant c

    doubling strategy: double the size

    Algorithmpush(o)""ift = S.length - 1then"" "Anew array of"" " " " "size "" "fori0tot do"" " "A[i]S[i]"" " "SA""t t + 1""S[t] o"

  • 8/3/2019 Ch4.Stacks Queues.handouts

    8/22

    1/31/11

    8

    15

    Comparison of the

    Strategies

    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 ofoperations, i.e., T(n)/n

    16

    Incremental Strategy Analysis

    We replace the array k= n/c times The total time T(n) of a series ofn push operations is

    proportional to

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

    n + ck(k+ 1)/2 Since c 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.handouts

    9/22

    1/31/11

    9

    17

    Doubling Strategy Analysis

    We replace the array k= log2ntimes

    The total time T(n) of a series ofn push operations is proportionalto

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

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

    operation is O(1)

    geometric series

    1

    2

    1

    4

    8

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

    10/22

    1/31/11

    10

    19

    Array-based Stack in C++

    template classArrayStack {private:

    int capacity; // stack capacityObject *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)

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

    11/22

    1/31/11

    11

    1/31/11 02:50Vectors 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 the

    Stack ADT takes O(1) time

    tnodes

    elements

    top

    1/31/11 02:50Vectors 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.handouts

    12/22

    1/31/11

    12

    Stack Summary

    Stack Operation Complexity for Different Implementations

    1/31/11 02:50Vectors 23

    Array

    Fixed-Size

    Array

    Expandable (doublingstrategy)

    List

    Singly-Linked

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

    Push(o) O(1) O(n) Worst Case

    O(1) Best CaseO(1) Average Case

    O(1)

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

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

    Queues

    24

  • 8/3/2019 Ch4.Stacks Queues.handouts

    13/22

    1/31/11

    13

    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++

    26

    The Queue ADT (4.3.1) The Queue ADT stores

    arbitrary 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.handouts

    14/22

    1/31/11

    14

    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)

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

    15/22

    1/31/11

    15

    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 location ris kept empty

    Q

    0 1 2 rf

    normal configuration

    Q

    0 1 2 fr

    wrapped-around configuration

    30

    Queue Operations

    We use themodulo operator(remainder ofdivision)

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

    16/22

    1/31/11

    16

    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

    32

    Queue Operations (cont.)

    Operation dequeuethrows an exception ifthe queue is empty

    This exception isspecified 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.handouts

    17/22

    1/31/11

    17

    Performance and Limitations

    - array-based implementation of queue ADT Performance

    Let n be the number of elements in the stackThe space used is O(n)Each operation runs in time O(1)

    LimitationsThe 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

    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 strategyO(1) with the doubling strategy

  • 8/3/2019 Ch4.Stacks Queues.handouts

    18/22

    1/31/11

    18

    1/31/11 02:50Vectors 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

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

    19/22

    1/31/11

    19

    37

    Informal C++ Queue Interface

    Informal C++interface for ourQueue ADT

    Requires thedefinition of classEmptyQueueException

    No correspondingbuilt-in STL class

    template classQueue{public:

    int size();bool isEmpty();Object& front()

    throw(EmptyQueueException );voidenqueue(Object o);Object dequeue()

    throw(EmptyQueueException);};

    Queue Summary

    Queue Operation Complexity for Different Implementations

    1/31/11 02:50Vectors 38

    Array

    Fixed-Size

    Array

    Expandable (doublingstrategy)

    List

    Singly-Linked

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

    enqueue(o) O(1) O(n) Worst Case

    O(1) Best CaseO(1) Average Case

    O(1)

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

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

  • 8/3/2019 Ch4.Stacks Queues.handouts

    20/22

    1/31/11

    20

    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): inserts

    element 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 the

    front 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 of

    dequeue or front on an emptyqueue throws anEmptyDequeException

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

    21/22

    1/31/11

    21

    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 theDeque ADT takes O(1) time

    lastfirst

    elements

    first

    Performance and Limitations- doubly linked list implementation of deque ADT

    PerformanceLet n be the number of elements in the stackThe space used is O(n)Each operation runs in time O(1)

    LimitationsNOTE: we do not have the limitation of the array

    based implementation on the size of the stack b/c

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

  • 8/3/2019 Ch4.Stacks Queues.handouts

    22/22

    1/31/11

    Deque Summary

    Deque Operation Complexity for Different Implementations

    1/31/11 02:50Vectors 43

    Array

    Fixed-Size

    Array

    Expandable(doubling strategy)

    List

    Singly-Linked

    List

    Doubly-Linked

    removeFirst(),

    removeLast()

    O(1) O(1) O(n) for

    one at listtail, O(1) for

    other

    O(1)

    insertFirst(o),

    InsertLast(o)

    O(1) O(n) Worst Case

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