python
# Linked list node class
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Queue class
class Queue:
def __init__(self):
self.front = None # Queue front
self.rear = None # Queue rear
def is_empty(self):
return self.front is None
def enqueue(self, val):
new_node = ListNode(val)
if self.rear is None:
self.front = self.rear = new_node
return
self.rear.next = new_node
self.rear = new_node
def dequeue(self):
if self.is_empty():
return "Queue is empty"
val = self.front.val
self.front = self.front.next
if self.front is None:
self.rear = None
return val
def peek(self):
if self.is_empty():
return "Queue is empty"
return self.front.val
def size(self):
count = 0
cur = self.front
while cur:
count += 1
cur = cur.next
return count
def main():
# Create a new queue
my_queue = Queue()
# Check if the queue is empty
print("Is the queue empty?", my_queue.is_empty())
# Enqueue elements to the queue
my_queue.enqueue(1)
my_queue.enqueue(2)
my_queue.enqueue(3)
# Output the elements of the queue
print("Queue elements:")
cur = my_queue.front
while cur:
print(cur.val, end=" ")
cur = cur.next
print()
# Check the size of the queue
print("Queue size:", my_queue.size())
# Peek at the front element of the queue
print("Front element:", my_queue.peek())
# Dequeue elements from the queue
dequeued_item = my_queue.dequeue()
print("Dequeued item:", dequeued_item)
# Check the size of the queue after dequeue
print("Queue size after dequeue:", my_queue.size())
# Check if the queue is empty again
print("Is the queue empty now?", my_queue.is_empty())
# Output the elements of the queue
print("Queue elements:")
cur = my_queue.front
while cur:
print(cur.val, end=" ")
cur = cur.next
print()
if __name__ == "__main__":
main()
结果:
Is the queue empty? True
Queue elements:
1 2 3
Queue size: 3
Front element: 1
Dequeued item: 1
Queue size after dequeue: 2
Is the queue empty now? False
Queue elements:
2 3