SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
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 
Rear 
Queue
Queues (2) 
„ 
The queuesupports 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() return(N-f+r) mod N 
Algorithm isEmpty() return(f=r) 
Algorithm front() ifisEmpty() thenreturnQueueemptyexceptionreturnQ[f] 
Algorithm dequeue() ifisEmpty() thenreturn QueueemptyexceptionQ[f] ←nullf←(f+1)modN 
Algorithm enqueue(o) ifsize = N -1 thenreturnQueuefullexceptionQ[r]←or←(r +1)modN
…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? 
Implementing Queue with Linked List
… 
Dequeue -advance head reference 
… 
Inserting at the head is just as easy 
Linked List Implementation
…Enqueue -create a new node at the tail 
… 
chain it and move the tail reference 
… 
How about removing at the tail? 
Linked List Implementation (2)
Double-Ended Queue 
…A double-ended queue, or deque, supports insertionand deletion from the front and back 
… 
The deque supports six fundamental methods 
… 
InsertFirst(S:ADT, o:element):ADT -Inserts eat the beginning of deque 
… 
InsertLast(S:ADT, o:element):ADT -Inserts eat 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 nextand a prevlink 
… 
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 addtwo special nodes to the ends of the lists: the headerand 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 avalid prev reference but a null next reference. 
… 
The header and trailer nodes are sentinelor“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 IntegerArrayStackclass that adapts ArrayStackto 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 sentinelis 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 –1downto rdo 
S[i+1] ←S[i] 
S[r] ←e 
n ←n + 1 
Algorithm removeAtRank(r): 
e ←S[r] 
for i = rto n -2do 
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
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++; 
} 
Java Implementation
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 itDLNode 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 
DLNodenode; 
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) andinsertAfterNode(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 PositionADT 
… 
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()

Más contenido relacionado

La actualidad más candente (20)

Lec12
Lec12Lec12
Lec12
 
Lec8
Lec8Lec8
Lec8
 
Lec5
Lec5Lec5
Lec5
 
Lec11
Lec11Lec11
Lec11
 
Lec10
Lec10Lec10
Lec10
 
Lec2
Lec2Lec2
Lec2
 
Lec17
Lec17Lec17
Lec17
 
skip list
skip listskip list
skip list
 
Lec18
Lec18Lec18
Lec18
 
Queues
QueuesQueues
Queues
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
Heaps
HeapsHeaps
Heaps
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
Tree Traversal
Tree TraversalTree Traversal
Tree Traversal
 
Threaded binary tree
Threaded binary treeThreaded binary tree
Threaded binary tree
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
Expression trees
Expression treesExpression trees
Expression trees
 

Destacado (16)

Lec4
Lec4Lec4
Lec4
 
PFDS 11.2 catenable double ended queue
PFDS 11.2 catenable double ended queuePFDS 11.2 catenable double ended queue
PFDS 11.2 catenable double ended queue
 
Lec6
Lec6Lec6
Lec6
 
Cursos sql server .net visual basic octubre 2010
Cursos sql server .net visual basic octubre 2010 Cursos sql server .net visual basic octubre 2010
Cursos sql server .net visual basic octubre 2010
 
I 7
I 7I 7
I 7
 
List classes
List classesList classes
List classes
 
Java Stack (Pilha)
Java Stack (Pilha)Java Stack (Pilha)
Java Stack (Pilha)
 
Applications of queues ii
Applications of queues   iiApplications of queues   ii
Applications of queues ii
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and Algorithms
 
Lec19
Lec19Lec19
Lec19
 
Lec21
Lec21Lec21
Lec21
 
Lec20
Lec20Lec20
Lec20
 
Lec22
Lec22Lec22
Lec22
 
Lec23
Lec23Lec23
Lec23
 
Build a Better Entrepreneur Pitch Deck
Build a Better Entrepreneur Pitch DeckBuild a Better Entrepreneur Pitch Deck
Build a Better Entrepreneur Pitch Deck
 

Similar a Lec3

queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddumaneesh boddu
 
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
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
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
 
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
 
Data Structure -List Stack Queue
Data Structure -List Stack QueueData Structure -List Stack Queue
Data Structure -List Stack Queuesurya pandian
 
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
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updatedvrgokila
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptxSajalFayyaz
 

Similar a Lec3 (20)

queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Vectors,squence & list
Vectors,squence & listVectors,squence & list
Vectors,squence & list
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
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
 
Queue
QueueQueue
Queue
 
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
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
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
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
2 b queues
2 b queues2 b queues
2 b queues
 
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
 
Data Structure -List Stack Queue
Data Structure -List Stack QueueData Structure -List Stack Queue
Data Structure -List Stack Queue
 
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
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
07 java collection
07 java collection07 java collection
07 java collection
 
Data structures
Data structuresData structures
Data structures
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptx
 

Más de Nikhil Chilwant (20)

The joyless economy
The joyless economyThe joyless economy
The joyless economy
 
IIT Delhi training pioneer ct (acemicromatic )
IIT Delhi training pioneer ct (acemicromatic )IIT Delhi training pioneer ct (acemicromatic )
IIT Delhi training pioneer ct (acemicromatic )
 
Lec39
Lec39Lec39
Lec39
 
Lec38
Lec38Lec38
Lec38
 
Lec37
Lec37Lec37
Lec37
 
Lec36
Lec36Lec36
Lec36
 
Lec35
Lec35Lec35
Lec35
 
Lec34
Lec34Lec34
Lec34
 
Lec33
Lec33Lec33
Lec33
 
Lec32
Lec32Lec32
Lec32
 
Lec30
Lec30Lec30
Lec30
 
Lec29
Lec29Lec29
Lec29
 
Lec28
Lec28Lec28
Lec28
 
Lec27
Lec27Lec27
Lec27
 
Lec26
Lec26Lec26
Lec26
 
Lec25
Lec25Lec25
Lec25
 
Lec24
Lec24Lec24
Lec24
 
Lec23
Lec23Lec23
Lec23
 
Lec21
Lec21Lec21
Lec21
 
Lec20
Lec20Lec20
Lec20
 

Último

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 

Último (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

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 Rear Queue
  • 3. Queues (2) „ The queuesupports 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() return(N-f+r) mod N Algorithm isEmpty() return(f=r) Algorithm front() ifisEmpty() thenreturnQueueemptyexceptionreturnQ[f] Algorithm dequeue() ifisEmpty() thenreturn QueueemptyexceptionQ[f] ←nullf←(f+1)modN Algorithm enqueue(o) ifsize = N -1 thenreturnQueuefullexceptionQ[r]←or←(r +1)modN
  • 8. …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? Implementing Queue with Linked List
  • 9. … Dequeue -advance head reference … Inserting at the head is just as easy Linked List Implementation
  • 10. …Enqueue -create a new node at the tail … chain it and move the tail reference … How about removing at the tail? Linked List Implementation (2)
  • 11. Double-Ended Queue …A double-ended queue, or deque, supports insertionand deletion from the front and back … The deque supports six fundamental methods … InsertFirst(S:ADT, o:element):ADT -Inserts eat the beginning of deque … InsertLast(S:ADT, o:element):ADT -Inserts eat 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 nextand a prevlink … 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 addtwo special nodes to the ends of the lists: the headerand 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 avalid prev reference but a null next reference. … The header and trailer nodes are sentinelor“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 IntegerArrayStackclass that adapts ArrayStackto 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 sentinelis an elegant implementation of a stack or a queue
  • 19.
  • 20.
  • 21.
  • 22. Sequences „Vectors „ Positions „ Lists „ General Sequences
  • 23. 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
  • 24. Array-Based Implementation Algorithm insertAtRank(r,e): for i= n –1downto rdo S[i+1] ←S[i] S[r] ←e n ←n + 1 Algorithm removeAtRank(r): e ←S[r] for i = rto n -2do S[i] ←S[i + 1] n ←n -1 return
  • 25. Array-Based Implementation (contd.) Time complexity of the various methods:
  • 26. Implem. with a Doubly Linked List the list before insertion creating a new node for insertion: the list after insertion
  • 27. 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++; } Java Implementation
  • 28. Implementation with a Doubly Linked List the list before deletion deleting a node after deletion
  • 29. 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 itDLNode prev= node.getPrev(); // node after it prev.setNext(next); next.setPrev(prev); size--; return node.getElement(); // returns the element of the deleted node }
  • 30. Java Implementation (contd.) private DLNode nodeAtRank(int rank) { //auxiliary method to find node of element with given rank DLNodenode; 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; }
  • 31. Nodes …Linked lists support the efficient execution of node-based operations: … removeAtNode(Node v) andinsertAfterNode(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.
  • 32. From Nodes to Positions …We introduce the PositionADT … 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
  • 33. 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
  • 34. 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
  • 35. Comparison of Sequence Implementations
  • 36. 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()