SlideShare une entreprise Scribd logo
1  sur  33
Queues and Linked Lists
Queues
Linked Lists
Double-Ended Queues
Queues
 A queue differs from a stack in that its insertion
  and removal routines follows the first-in-first-out
  (FIFO) principle.
 Elements may be inserted at any time, but only
  the element which has been in the queue the
  longest may be removed.
 Elements are inserted at the rear (enqueued) and
  removed from the front (dequeued)
         Front           Queue           Rear
Queues (2)
   The queue supports three fundamental
    methods:
     New():ADT     – Creates an empty queue
     Enqueue(S:ADT, o:element):ADT - Inserts object o
      at the rear of the queue
     Dequeue(S:ADT):ADT - Removes the object from the
      front of the queue; an error occurs if the queue is
      empty
     Front(S:ADT):element - Returns, but does not
      remove, the front element; an error occurs if the
      queue is empty
Queues (3)
   These support methods should also be
    defined:
     Size(S:ADT):integer
     IsEmpty(S:ADT):boolean
   Axioms:
     Front(Enqueue(New(), v)) = v
     Dequeque(Enqueue(New(), v)) = New()
     Front(Enqueue(Enqueue(Q, w), v)) =
      Front(Enqueue(Q, w))
     Dequeue(Enqueue(Enqueue(Q, w), v)) =
      Enqueue(Dequeue(Enqueue(Q, w)), v)
An Array Implementation
 Create a queue using an array in a circular
  fashion
 A maximum size N is specified.
 The queue consists of an N-element array
  Q and two integer variables:
     f, index of the front element (head – for
      dequeue)
     r, index of the element after the rear one (tail
      – for enqueue)
An Array Implementation (2)
   “wrapped around” configuration




   what does f=r mean?
An Array Implementation (3)
    Pseudo code
Algorithm size()            Algorithm dequeue()
return (N-f+r) mod N        if isEmpty() then
                            return Queueemptyexception
Algorithm isEmpty()
                            Q[f]    null
return (f=r)
                            f (f+1)modN
Algorithm front()
if isEmpty() then
                           Algorithm enqueue(o)
return Queueemptyexception
                           if size = N - 1 then
return Q[f]
                           return Queuefullexception
                           Q[r]      o
                           r     (r +1)modN
Implementing Queue with Linked List
   Nodes (data, pointer) connected in a chain by
    links




   The head of the list is the front of the queue, the
    tail of the list is the rear of the queue. Why not
    the opposite?
Linked List Implementation



   Dequeue - advance head reference




   Inserting at the head is just as easy
Linked List Implementation (2)
   Enqueue - create a new node at the tail




   chain it and move the tail reference




   How about removing at the tail?
Double-Ended Queue
 A double-ended queue, or deque, supports
  insertion and deletion from the front and back
 The deque supports six fundamental methods
     InsertFirst(S:ADT, o:element):ADT - Inserts e at the
      beginning of deque
     InsertLast(S:ADT, o:element):ADT - Inserts e at end of
      deque
     RemoveFirst(S:ADT):ADT – Removes the first element
     RemoveLast(S:ADT):ADT – Removes the last element
     First(S:ADT):element and Last(S:ADT):element –
      Returns the first and the last elements
Doubly Linked Lists
 Deletions at the tail of a singly linked list cannot be
  done in constant time
 To implement a deque, we use a doubly linked
  list




 A node of a doubly linked list has a next and a
  prev link
 Then, all the methods of a deque have a constant
  (that is, O(1)) running time.
Doubly Linked Lists (2)
   When implementing a doubly linked lists, we add
    two special nodes to the ends of the lists: the
    header and trailer nodes
     The header node goes before the first list element. It
      has a valid next link but a null prev link.
     The trailer node goes after the last element. It has a
      valid prev reference but a null next reference.
   The header and trailer nodes are sentinel or
    “dummy” nodes because they do not store
    elements
Stacks with Deques
   Implementing ADTs using implementations
    of other ADTs as building blocks

         Stack Method       Deque
                        Implementation
            size()          size()
           isEmpty()      isEmpty()
             top()          last()
           push(o)       insertLast(o)
             pop()       removeLast()
Queues with Deques

     Queue Method       Deque
                    Implementation
         size()         size()
       isEmpty()      isEmpty()
        front()          first()
      enqueue(o)     insertLast(o)
       dequeue()     removeFirst()
The Adaptor Pattern
Using  a deque to implement a stack or queue is an
example of the adaptor pattern. Adaptor patterns
implement a class by using methods of another class
In general, adaptor classes specialize general
classes
Two such applications
  Specialize  a general class by changing some methods eg
  implementing a stack with a deque.
  Specialize the types of objects used by a general class eg
  defining an IntegerArrayStack class that adapts ArrayStack
  to only store integers.
Circular Lists
   No end and no beginning of the list, only one
    pointer as an entry point
   Circular doubly linked list with a sentinel is an
    elegant implementation of a stack or a queue
Sequences
 Vectors
 Positions
 Lists
 General Sequences
The Vector ADT
A sequence S (with n elements) that supports the following
  methods:
 elemAtRank(r): Return the element of S with rank r; an
  error occurs if r < 0 or r > n -1
 replaceAtRank(r,e): Replace the element at rank r with e
  and return the old element; an error condition occurs if
  r < 0 or r > n - 1
 insertAtRank(r,e): Insert a new element into S which will
  have rank r; an error occurs if r< 0 or r > n
 removeAtRank(r): Remove from S the element at rank r;
  an error occurs if r < 0 or r > n - 1
Array-Based Implementation
Algorithm insertAtRank(r,e):
for i = n – 1 downto r do
    S[i+1]    S[i]
S[r]     e
n     n+1


Algorithm removeAtRank(r):
e     S[r]
for i = r to n - 2 do
    S[i]    S[i + 1]
n     n-1
return
Array-Based Implementation (contd.)

Time complexity of the various methods:
Implem. with a Doubly Linked List
the list before insertion




                            creating a new node for
                            insertion:




the list after insertion
Java Implementation
public void insertAtRank (int rank, Object element)
    throws BoundaryViolationException {
if (rank < 0 || rank > size())
    throw new BoundaryViolationException(“invalid rank”);
DLNode next = nodeAtRank(rank);
                        // the new node will be right before this
DLNode prev = next.getPrev();
                           // the new node will be right after this
DLNode node = new DLNode(element, prev, next);
                     // new node knows about its next & prev.
               // Now we tell next & prev about the new node.
next.setPrev(node);
prev.setNext(node);
size++;
}
Implementation with a Doubly Linked
List
the list before
deletion



deleting a node



after deletion
Java Implementation
public Object removeAtRank (int rank)
         throws BoundaryViolationException {
if (rank < 0 || rank > size()-1)
      throw new BoundaryViolationException(“Invalid rank.”);
DLNode node = nodeAtRank(rank); // node to be removed
DLNode next = node.getNext();                   // node before it
DLNode prev = node.getPrev();                      // node after it
prev.setNext(next);
next.setPrev(prev);
size--;
return node.getElement();
                     // returns the element of the deleted node
 }
Java Implementation (contd.)
private DLNode nodeAtRank (int rank) {
      //auxiliary method to find node of element with given rank
DLNode node;
if (rank <= size()/2) {                     //scan forward from head
   node = header.getNext();
   for (int i=0; i < rank; i++)
       node = node.getNext();
} else {                                //scan backward from the tail
        node = trailer.getPrev();
        for (int i=0; i < size()-rank-1 ; i++)
             node = node.getPrev();
}
return node;
}
Nodes
 Linked lists support the efficient execution of
  node-based operations:
 removeAtNode(Node v) and
  insertAfterNode(Node v, Object e), would be
  O(1).
 However, node-based operations are not
  meaningful in an array-based implementation
  because there are no nodes in an array.
 Nodes are implementation-specific.
 Dilemma:
     If we do not define node based operations, we are not
      taking full advantage of doubly-linked lists.
     If we do define them, we violate the generality of ADTs.
From Nodes to Positions

 We  introduce the Position ADT
 Intuitive notion of “place” of an element.
 Positions have only one method:
  element(): Returns the element at this
  position
 Positions are defined relative to other
  positions (before/after relation)
 Positions are not tied to an element or
  rank
The List ADT
 ADT with position-based methods
 generic methods: size(), isEmpty()
 query methods: isFirst(p), isLast(p)
 accessor methods: first(), last(), before(p), after(p)
 update methods
    swapElements(p,q), replaceElement(p,e)
    insertFirst(e), insertLast(e)
    insertBefore(p,e), insertAfter(p,e)
    remove(p)
 each method takes O(1) time if implemented with
  a doubly linked list
The Sequence ADT
 Combines the Vector
  and List ADT (multiple
  inheritance)
 Adds methods that
  bridge between ranks
  and positions
     atRank(r)   returns a
      position
     rankOf(p) returns an
      integer rank
 An   array-based implementation needs to use
    objects to represent the positions
Comparison of Sequence
Implementations
Iterators
 Abstraction of the process of scanning through a
  collection of elements
 Encapsulates the notions of “place” and “next”
 Extends the position ADT
 Generic and specialized iterators
 ObjectIterator: hasNext(), nextObject(), object()
 PositionIterator: nextPosition()
 Useful methods that return iterators:
  elements(), positions()

Contenu connexe

Tendances (20)

Lec2
Lec2Lec2
Lec2
 
Lec5
Lec5Lec5
Lec5
 
Lec10
Lec10Lec10
Lec10
 
Lec12
Lec12Lec12
Lec12
 
Lec5
Lec5Lec5
Lec5
 
Lec20
Lec20Lec20
Lec20
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithm
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
Lec11
Lec11Lec11
Lec11
 
Selection sort
Selection sortSelection sort
Selection sort
 
Lecture 4 asymptotic notations
Lecture 4   asymptotic notationsLecture 4   asymptotic notations
Lecture 4 asymptotic notations
 
Algorithm And analysis Lecture 03& 04-time complexity.
 Algorithm And analysis Lecture 03& 04-time complexity. Algorithm And analysis Lecture 03& 04-time complexity.
Algorithm And analysis Lecture 03& 04-time complexity.
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Algorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IAlgorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms I
 
Python matplotlib cheat_sheet
Python matplotlib cheat_sheetPython matplotlib cheat_sheet
Python matplotlib cheat_sheet
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Heaps
HeapsHeaps
Heaps
 
Dictionary
DictionaryDictionary
Dictionary
 
Red Black Tree Insertion & Deletion
Red Black Tree Insertion & DeletionRed Black Tree Insertion & Deletion
Red Black Tree Insertion & Deletion
 

En vedette

Elearning - Rich Media Search
Elearning - Rich Media SearchElearning - Rich Media Search
Elearning - Rich Media Searchlanglearner
 
Reported speech j y f
Reported speech j y fReported speech j y f
Reported speech j y ffuenxesla
 
Intro parcmarin amp2010-anglais
Intro parcmarin amp2010-anglaisIntro parcmarin amp2010-anglais
Intro parcmarin amp2010-anglaiscwfli2010
 
Chapter 1 market & marketing
Chapter 1 market & marketingChapter 1 market & marketing
Chapter 1 market & marketingHo Cao Viet
 
Market research process
Market research processMarket research process
Market research processHo Cao Viet
 
Direct mailresponsesuccessandfulfillment
Direct mailresponsesuccessandfulfillmentDirect mailresponsesuccessandfulfillment
Direct mailresponsesuccessandfulfillmentPatti Mazzara
 
Fascinating....... mother russia
Fascinating....... mother russiaFascinating....... mother russia
Fascinating....... mother russiafilipj2000
 
Maherwhitepaperon at universaldesign112111v2 0
Maherwhitepaperon at universaldesign112111v2 0Maherwhitepaperon at universaldesign112111v2 0
Maherwhitepaperon at universaldesign112111v2 0Pat Maher
 
Using Data to Understand the Brain
Using Data to Understand the BrainUsing Data to Understand the Brain
Using Data to Understand the Brainjakehofman
 
The Zoo Amberlyn Marshall
The Zoo Amberlyn MarshallThe Zoo Amberlyn Marshall
The Zoo Amberlyn Marshallamberlyn284
 
10강 기업교육론 20110504
10강 기업교육론 2011050410강 기업교육론 20110504
10강 기업교육론 20110504조현경
 
Proceeding aciar beefcattle_ias team_jan_2014
Proceeding aciar beefcattle_ias team_jan_2014Proceeding aciar beefcattle_ias team_jan_2014
Proceeding aciar beefcattle_ias team_jan_2014Ho Cao Viet
 
How to Make Mount Gay Rum Super Premium
How to Make Mount Gay Rum Super PremiumHow to Make Mount Gay Rum Super Premium
How to Make Mount Gay Rum Super PremiumDexter King, MBA
 
Jim sterne terametric_twitter-webinar_120910
Jim sterne terametric_twitter-webinar_120910Jim sterne terametric_twitter-webinar_120910
Jim sterne terametric_twitter-webinar_120910Terametric
 
Praag bij nacht
Praag bij nachtPraag bij nacht
Praag bij nachtfilipj2000
 
Bca 2010 draft
Bca 2010 draftBca 2010 draft
Bca 2010 draftk20eagan74
 
Charter of demands -From the Resident's of Dwarka,Delhi Sub city
Charter of demands -From the Resident's of  Dwarka,Delhi Sub cityCharter of demands -From the Resident's of  Dwarka,Delhi Sub city
Charter of demands -From the Resident's of Dwarka,Delhi Sub cityMadhukar Varshney
 

En vedette (20)

Elearning - Rich Media Search
Elearning - Rich Media SearchElearning - Rich Media Search
Elearning - Rich Media Search
 
Reported speech j y f
Reported speech j y fReported speech j y f
Reported speech j y f
 
Intro parcmarin amp2010-anglais
Intro parcmarin amp2010-anglaisIntro parcmarin amp2010-anglais
Intro parcmarin amp2010-anglais
 
Chapter 1 market & marketing
Chapter 1 market & marketingChapter 1 market & marketing
Chapter 1 market & marketing
 
Market research process
Market research processMarket research process
Market research process
 
Direct mailresponsesuccessandfulfillment
Direct mailresponsesuccessandfulfillmentDirect mailresponsesuccessandfulfillment
Direct mailresponsesuccessandfulfillment
 
Fascinating....... mother russia
Fascinating....... mother russiaFascinating....... mother russia
Fascinating....... mother russia
 
Maherwhitepaperon at universaldesign112111v2 0
Maherwhitepaperon at universaldesign112111v2 0Maherwhitepaperon at universaldesign112111v2 0
Maherwhitepaperon at universaldesign112111v2 0
 
Using Data to Understand the Brain
Using Data to Understand the BrainUsing Data to Understand the Brain
Using Data to Understand the Brain
 
The Zoo Amberlyn Marshall
The Zoo Amberlyn MarshallThe Zoo Amberlyn Marshall
The Zoo Amberlyn Marshall
 
10강 기업교육론 20110504
10강 기업교육론 2011050410강 기업교육론 20110504
10강 기업교육론 20110504
 
Proceeding aciar beefcattle_ias team_jan_2014
Proceeding aciar beefcattle_ias team_jan_2014Proceeding aciar beefcattle_ias team_jan_2014
Proceeding aciar beefcattle_ias team_jan_2014
 
STEM Powers Jets
STEM Powers JetsSTEM Powers Jets
STEM Powers Jets
 
La nuit
La nuitLa nuit
La nuit
 
How to Make Mount Gay Rum Super Premium
How to Make Mount Gay Rum Super PremiumHow to Make Mount Gay Rum Super Premium
How to Make Mount Gay Rum Super Premium
 
Jim sterne terametric_twitter-webinar_120910
Jim sterne terametric_twitter-webinar_120910Jim sterne terametric_twitter-webinar_120910
Jim sterne terametric_twitter-webinar_120910
 
Draw1.
Draw1.Draw1.
Draw1.
 
Praag bij nacht
Praag bij nachtPraag bij nacht
Praag bij nacht
 
Bca 2010 draft
Bca 2010 draftBca 2010 draft
Bca 2010 draft
 
Charter of demands -From the Resident's of Dwarka,Delhi Sub city
Charter of demands -From the Resident's of  Dwarka,Delhi Sub cityCharter of demands -From the Resident's of  Dwarka,Delhi Sub city
Charter of demands -From the Resident's of Dwarka,Delhi Sub city
 

Similaire à Lec3

queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfaromalcom
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queueRai University
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queueRai University
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updatedvrgokila
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
23 stacks-queues-deques
23 stacks-queues-deques23 stacks-queues-deques
23 stacks-queues-dequesRishabh Jindal
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueRai University
 

Similaire à Lec3 (20)

Vectors,squence & list
Vectors,squence & listVectors,squence & list
Vectors,squence & list
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdf
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
2 b queues
2 b queues2 b queues
2 b queues
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
23 stacks-queues-deques
23 stacks-queues-deques23 stacks-queues-deques
23 stacks-queues-deques
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
Queues
QueuesQueues
Queues
 

Plus de Anjneya Varshney (6)

Lec23
Lec23Lec23
Lec23
 
Lec22
Lec22Lec22
Lec22
 
Lec21
Lec21Lec21
Lec21
 
Lec19
Lec19Lec19
Lec19
 
Lec16
Lec16Lec16
Lec16
 
Lec13
Lec13Lec13
Lec13
 

Lec3

  • 1. Queues and Linked Lists Queues Linked Lists Double-Ended Queues
  • 2. Queues  A queue differs from a stack in that its insertion and removal routines follows the first-in-first-out (FIFO) principle.  Elements may be inserted at any time, but only the element which has been in the queue the longest may be removed.  Elements are inserted at the rear (enqueued) and removed from the front (dequeued) Front Queue Rear
  • 3. Queues (2)  The queue supports three fundamental methods:  New():ADT – Creates an empty queue  Enqueue(S:ADT, o:element):ADT - Inserts object o at the rear of the queue  Dequeue(S:ADT):ADT - Removes the object from the front of the queue; an error occurs if the queue is empty  Front(S:ADT):element - Returns, but does not remove, the front element; an error occurs if the queue is empty
  • 4. Queues (3)  These support methods should also be defined:  Size(S:ADT):integer  IsEmpty(S:ADT):boolean  Axioms:  Front(Enqueue(New(), v)) = v  Dequeque(Enqueue(New(), v)) = New()  Front(Enqueue(Enqueue(Q, w), v)) = Front(Enqueue(Q, w))  Dequeue(Enqueue(Enqueue(Q, w), v)) = Enqueue(Dequeue(Enqueue(Q, w)), v)
  • 5. An Array Implementation  Create a queue using an array in a circular fashion  A maximum size N is specified.  The queue consists of an N-element array Q and two integer variables:  f, index of the front element (head – for dequeue)  r, index of the element after the rear one (tail – for enqueue)
  • 6. An Array Implementation (2)  “wrapped around” configuration  what does f=r mean?
  • 7. An Array Implementation (3)  Pseudo code Algorithm size() Algorithm dequeue() return (N-f+r) mod N if isEmpty() then return Queueemptyexception Algorithm isEmpty() Q[f] null return (f=r) f (f+1)modN Algorithm front() if isEmpty() then Algorithm enqueue(o) return Queueemptyexception if size = N - 1 then return Q[f] return Queuefullexception Q[r] o r (r +1)modN
  • 8. Implementing Queue with Linked List  Nodes (data, pointer) connected in a chain by links  The head of the list is the front of the queue, the tail of the list is the rear of the queue. Why not the opposite?
  • 9. Linked List Implementation  Dequeue - advance head reference  Inserting at the head is just as easy
  • 10. Linked List Implementation (2)  Enqueue - create a new node at the tail  chain it and move the tail reference  How about removing at the tail?
  • 11. Double-Ended Queue  A double-ended queue, or deque, supports insertion and deletion from the front and back  The deque supports six fundamental methods  InsertFirst(S:ADT, o:element):ADT - Inserts e at the beginning of deque  InsertLast(S:ADT, o:element):ADT - Inserts e at end of deque  RemoveFirst(S:ADT):ADT – Removes the first element  RemoveLast(S:ADT):ADT – Removes the last element  First(S:ADT):element and Last(S:ADT):element – Returns the first and the last elements
  • 12. Doubly Linked Lists  Deletions at the tail of a singly linked list cannot be done in constant time  To implement a deque, we use a doubly linked list  A node of a doubly linked list has a next and a prev link  Then, all the methods of a deque have a constant (that is, O(1)) running time.
  • 13. Doubly Linked Lists (2)  When implementing a doubly linked lists, we add two special nodes to the ends of the lists: the header and trailer nodes  The header node goes before the first list element. It has a valid next link but a null prev link.  The trailer node goes after the last element. It has a valid prev reference but a null next reference.  The header and trailer nodes are sentinel or “dummy” nodes because they do not store elements
  • 14.
  • 15. Stacks with Deques  Implementing ADTs using implementations of other ADTs as building blocks Stack Method Deque Implementation size() size() isEmpty() isEmpty() top() last() push(o) insertLast(o) pop() removeLast()
  • 16. Queues with Deques Queue Method Deque Implementation size() size() isEmpty() isEmpty() front() first() enqueue(o) insertLast(o) dequeue() removeFirst()
  • 17. The Adaptor Pattern Using a deque to implement a stack or queue is an example of the adaptor pattern. Adaptor patterns implement a class by using methods of another class In general, adaptor classes specialize general classes Two such applications Specialize a general class by changing some methods eg implementing a stack with a deque. Specialize the types of objects used by a general class eg defining an IntegerArrayStack class that adapts ArrayStack to only store integers.
  • 18. Circular Lists  No end and no beginning of the list, only one pointer as an entry point  Circular doubly linked list with a sentinel is an elegant implementation of a stack or a queue
  • 19. Sequences  Vectors  Positions  Lists  General Sequences
  • 20. The Vector ADT A sequence S (with n elements) that supports the following methods:  elemAtRank(r): Return the element of S with rank r; an error occurs if r < 0 or r > n -1  replaceAtRank(r,e): Replace the element at rank r with e and return the old element; an error condition occurs if r < 0 or r > n - 1  insertAtRank(r,e): Insert a new element into S which will have rank r; an error occurs if r< 0 or r > n  removeAtRank(r): Remove from S the element at rank r; an error occurs if r < 0 or r > n - 1
  • 21. Array-Based Implementation Algorithm insertAtRank(r,e): for i = n – 1 downto r do S[i+1] S[i] S[r] e n n+1 Algorithm removeAtRank(r): e S[r] for i = r to n - 2 do S[i] S[i + 1] n n-1 return
  • 22. Array-Based Implementation (contd.) Time complexity of the various methods:
  • 23. Implem. with a Doubly Linked List the list before insertion creating a new node for insertion: the list after insertion
  • 24. Java Implementation public void insertAtRank (int rank, Object element) throws BoundaryViolationException { if (rank < 0 || rank > size()) throw new BoundaryViolationException(“invalid rank”); DLNode next = nodeAtRank(rank); // the new node will be right before this DLNode prev = next.getPrev(); // the new node will be right after this DLNode node = new DLNode(element, prev, next); // new node knows about its next & prev. // Now we tell next & prev about the new node. next.setPrev(node); prev.setNext(node); size++; }
  • 25. Implementation with a Doubly Linked List the list before deletion deleting a node after deletion
  • 26. Java Implementation public Object removeAtRank (int rank) throws BoundaryViolationException { if (rank < 0 || rank > size()-1) throw new BoundaryViolationException(“Invalid rank.”); DLNode node = nodeAtRank(rank); // node to be removed DLNode next = node.getNext(); // node before it DLNode prev = node.getPrev(); // node after it prev.setNext(next); next.setPrev(prev); size--; return node.getElement(); // returns the element of the deleted node }
  • 27. Java Implementation (contd.) private DLNode nodeAtRank (int rank) { //auxiliary method to find node of element with given rank DLNode node; if (rank <= size()/2) { //scan forward from head node = header.getNext(); for (int i=0; i < rank; i++) node = node.getNext(); } else { //scan backward from the tail node = trailer.getPrev(); for (int i=0; i < size()-rank-1 ; i++) node = node.getPrev(); } return node; }
  • 28. Nodes  Linked lists support the efficient execution of node-based operations:  removeAtNode(Node v) and insertAfterNode(Node v, Object e), would be O(1).  However, node-based operations are not meaningful in an array-based implementation because there are no nodes in an array.  Nodes are implementation-specific.  Dilemma:  If we do not define node based operations, we are not taking full advantage of doubly-linked lists.  If we do define them, we violate the generality of ADTs.
  • 29. From Nodes to Positions  We introduce the Position ADT  Intuitive notion of “place” of an element.  Positions have only one method: element(): Returns the element at this position  Positions are defined relative to other positions (before/after relation)  Positions are not tied to an element or rank
  • 30. The List ADT  ADT with position-based methods  generic methods: size(), isEmpty()  query methods: isFirst(p), isLast(p)  accessor methods: first(), last(), before(p), after(p)  update methods  swapElements(p,q), replaceElement(p,e)  insertFirst(e), insertLast(e)  insertBefore(p,e), insertAfter(p,e)  remove(p)  each method takes O(1) time if implemented with a doubly linked list
  • 31. The Sequence ADT  Combines the Vector and List ADT (multiple inheritance)  Adds methods that bridge between ranks and positions  atRank(r) returns a position  rankOf(p) returns an integer rank  An array-based implementation needs to use objects to represent the positions
  • 33. Iterators  Abstraction of the process of scanning through a collection of elements  Encapsulates the notions of “place” and “next”  Extends the position ADT  Generic and specialized iterators  ObjectIterator: hasNext(), nextObject(), object()  PositionIterator: nextPosition()  Useful methods that return iterators: elements(), positions()