Circular Queue Python
Solution 1:
If you don't have to implement this yourself, you can use the standard library deque
from collections import deque
circular_queue = deque([1,2], maxlen=4)
circular_queue.append(3)
circular_queue.extend([4])
# at this point you have [1,2,3,4]print(circular_queue.pop()) # [1,2,3] --> 4# key step. effectively rotate the pointer
circular_queue.rotate(-1) # negative to the left. positive to the right# at this point you have [2,3,1]print(circular_queue.pop()) # [2,3] --> 1
Solution 2:
Your problem is here:
self.tail + 1
but before, you initiated tail to be a Node:
self.tail = newNode
Thus the error.
Solution 3:
I'll try to point you in the right direction because it looks like you are trying to learn how to implement a circular queue and maybe learning to program at the same time. The error message is trying to tell you the variable self.tail is an object and that it cannot be added to a number (integer).
The line of code:
self.tail = (self.tail + 1) % 4
is the issue causing the error. However there are some core concepts which need to be understood before trying to fix that one line. For instance you don't have to make an array in your Node object. Self.item can be set to anything. and it seems it may be confusing the purpose of the circular queue. For example instead of
self.item = [None] * 4
you could use
self.item = item
then when you create the Node object you can use something like:
mycircularqueue = CircularQueue()
mycircularqueue.enqueue('cat')
mycircularqueue.enqueue('dog')
mycircularqueue.enqueue('mouse')
to add three items to your queue.
Solution 4:
If you just want to make the tail reach to the head.e.g.
list = [1,2,3]
list = list + list[0:1]
You'll get:
[1,2,3,1]
Maybe this is the easy way.
Post a Comment for "Circular Queue Python"