Linked & Sequential Queue in Python
1. Node
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __eq__(self, data):
return self.data == data
def __str__(self):
return str(self.data)
2. Sequential Queue
class ListQueue:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def empty(self):
return self.size() == 0
def front(self):
item = None
if not self.empty():
item = self.items[0]
return item
def rear(self):
return self.items[-1]
def traverse(self):
print(f"The current length: {self.size()}")
for val in self.items:
print(val)
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
item = None
if not self.empty():
item = self.items.pop(0)
return item
def clear(self):
self.items = []
def test_list_queue():
lq = ListQueue()
lq.enqueue("eggs")
lq.enqueue("ham")
lq.enqueue("spam")
lq.traverse()
print('-' * 20)
lq.dequeue()
lq.traverse()
3. Linked Queue
class LinkedQueue:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def size(self):
return self.size
def empty(self):
return self.size == 0
def clear(self):
self.size = 0
self.head = None
self.tail = None
def iter(self):
ptr = self.head
while ptr:
val = ptr.data
ptr = ptr.next
yield val
def traverse(self):
print(f"The current length: {self.size}")
for val in self.iter():
print(val)
def enqueue(self, data):
n = Node(data)
if not self.empty():
self.tail.next = n
else:
self.head = n
self.tail = n
self.size += 1
def dequeue(self):
item = None
if not self.empty():
item = self.head
self.head = self.head.next
if self.head is None:
self.tail = None
self.size -= 1
return item
def test_linked_queue():
q = LinkedQueue()
q.enqueue("eggs")
q.enqueue("ham")
q.enqueue("spam")
q.traverse()
print('-' * 20)
q.dequeue()
q.traverse()
4. Case: Media Player Queue
import random
import time
class Track:
def __init__(self, title=None):
self.title = title
self.length = random.randint(5, 10)
class MediaPlayer(ListQueue):
def __init__(self):
super().__init__()
pass
def add_track(self, track):
self.enqueue(track)
def play(self):
while not self.empty():
track = self.dequeue()
length = track.length
print(f"Now playing '{track.title}', Length = {track.length} seconds.")
time.sleep(length)
def test_media_player():
track1 = Track("Happy Birthday")
track2 = Track("ABC Song")
track3 = Track("Twinkle, Twinkle, Little Star")
track4 = Track("Let It Go")
track5 = Track("Weightless")
player = MediaPlayer()
player.enqueue(track1)
player.enqueue(track2)
player.enqueue(track3)
player.enqueue(track4)
player.enqueue(track5)
player.play()