Skip to content

Instantly share code, notes, and snippets.

@icaoberg
Last active January 15, 2025 10:00
Show Gist options
  • Save icaoberg/2969062 to your computer and use it in GitHub Desktop.
Save icaoberg/2969062 to your computer and use it in GitHub Desktop.
Simple queue in Python
# Author: Michelle Mackie
# Update: Ivan E. Cao-Berg
#
# Copyright (C) 2012-2025
# School of Computer Science
# Carnegie Mellon University
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# For additional information visit http://www.andrew.cmu.edu/~icaoberg or
# send email to [email protected]
class Queue:
def __init__(self):
"""
Initializes an empty queue.
"""
self.queue = []
def push(self, value):
"""
Adds a value to the end of the queue.
Args:
value (Any): The value to add to the queue.
Returns:
bool: True if the value was successfully added, False otherwise.
"""
if value is None:
return False
self.queue.append(value)
return True
def peek(self):
"""
Returns the front value of the queue without removing it.
Returns:
Any: The front value of the queue, or None if the queue is empty.
"""
return self.queue[0] if self.queue else None
def pop(self):
"""
Removes and returns the front value from the queue.
Returns:
bool: True if a value was successfully removed, False otherwise.
"""
if self.queue:
self.queue.pop(0)
return True
return False
def size(self):
"""
Returns the number of elements in the queue.
Returns:
int: The size of the queue.
"""
return len(self.queue)
def contains(self, value):
"""
Checks if the queue contains a specific value.
Args:
value (Any): The value to check for.
Returns:
bool: True if the value exists in the queue, False otherwise.
"""
return value in self.queue
def clear(self):
"""
Clears all elements from the queue.
"""
self.queue.clear()
def is_empty(self):
"""
Checks if the queue is empty.
Returns:
bool: True if the queue is empty, False otherwise.
"""
return len(self.queue) == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment