As FIFO data structure you could use next (with corresponding complexity):
list:append()amortized O(1) andpop(0)O(n)collections.deque-append()O(1) andpopleft()O(1)Queue.queue-get()O(1) andput()O(1) and etc. It is suitable for multi-threaded programming and based oncollections.dequeinternally.
Videos
As FIFO data structure you could use next (with corresponding complexity):
list:append()amortized O(1) andpop(0)O(n)collections.deque-append()O(1) andpopleft()O(1)Queue.queue-get()O(1) andput()O(1) and etc. It is suitable for multi-threaded programming and based oncollections.dequeinternally.
You can use a Queue
queue = Queue()
queue.put(0)
queue.put(1)
while not queue.empty():
print(queue.get())
So I understand the concept of queues being first in first out (just like standing in a line for something), but I don't really get what the lines where I commented "what does this line do?" do for the queue. This is code for a linked list queue in python provided by my professor so please correct me if I'm wrong.
class Queue :
def __init__( self ):
self._qhead = None
self._qtail = None
self._count = 0
def is_empty( self ):
return self._qhead is None
def __len__( self ):
return self._count
# Private storage class for creating the linked list nodes.
class _QueueNode:
def __init__( self, item ):
self.item = item
self.next = NoneHere is the code that I'm having trouble interpreting:
def enqueue( self, item ):
node = _QueueNode( item )
if self.is_empty() :
self._qhead = node
else :
self._qtail.next = node
self._qtail = node # what does this line do?
self._count += 1
Based on my understanding in the if statement, if nothing is in the queue, then the item will become the head of the linked list / the very first item of the queue. Otherwise, whatever the end / tail of the queue is, the pointer of that node will now point to the new item node. I just can't visualize what the self._qtail = node does to this linked list queue
def dequeue( self ):
assert not self.is_empty(), "Cannot dequeue from an empty queue."
node = self._qhead
if self._qhead is self._qtail : # what does this mean
self._qtail = None
self._qhead = self._qhead.next # what happens here?
self._count -= 1
return node.item Similarly, in the dequeue method it obviously cannot remove anything from an empty linked list so this code will assert an error. Because queues are FIFO, that means the very first element (in a regular list) / the head of the linked list, will be the one that is removed, so I understand the need to set up a node variable to be returned at the end of this method. However, someone please explain to me what the lines of code actually mean. Thanks in advance!