Full Transcript

IT1815 Queues o Dequeue – removes the head of the queue ▪ Method in Java: poll() Fundamentals...

IT1815 Queues o Dequeue – removes the head of the queue ▪ Method in Java: poll() Fundamentals ▪ Method in Python: popleft() A queue is an ordered list in which the first element added is the first element retrieved or removed (First-In, First-Out). Other queue operations: The first element in the queue is known as the head of the o Peek – retrieves the head of the queue queue. ▪ Method in Java: peek() Example: A queue of customers: Lisa, Jennie, Jisoo, Rose ▪ Syntax in Python: queue_name Lisa o Test whether queue is empty Jennie ▪ For Java, use the isEmpty() method. Jisoo ▪ For Python, use the if not condition, Rose followed by the queue name and a colon. Lisa is the customer who has been waiting the longest, while Example: Rose is the one who last arrived. Lisa will be the first customer queue = deque([]) removed from the queue. if not queue: Queues are used in any of the following: print("Queue is empty.") o CPU and disk scheduling o Serving requests on a single shared resource, such Other Queue Methods as a printer Java methods offer(), poll(), and peek() do not throw o Managing customers trying to get hold of a hotline. exceptions. The methods add(), remove(), and element() The methods of the Queue interface from the java.util perform the same tasks but throw exceptions. package are used to implement queues in Java. Since Other methods that can be used for both queues and lists are interfaces cannot be instantiated, LinkedList is used to the following: instantiate a Queue object. Function Java Python The methods of collections.deque are used to implement Delete all clear() clear() queues in Python. The import statement shall be from elements collections import deque. Copy all elements clone() copy() The list methods can also be used to implement queues in Return length/size size() len() Python. Reverse the Collections.reverse() reverse() The two (2) main queue operations are the following: elements o Enqueue – adds an item into the queue ▪ Method in Java: offer() References: Queue queue = new LinkedList(); Koffman, E. & Wolfgang, P. (2016). Data structures: Abstraction and design using Java. queue.offer("Lisa"); Hoboken: John Wiley & Sons, Inc. Python Software Foundation (n.d.). The Python tutorial. Retrieved from ▪ Method in Python: append() https://docs.python.org/3/tutorial/index.html queue = deque([]) queue.append("Jennie") 05 Handout 1 *Property of STI  [email protected] Page 1 of 1

Use Quizgecko on...
Browser
Browser