Skip to content

Conversation

@huzaifarehman1
Copy link

@huzaifarehman1 huzaifarehman1 commented Sep 14, 2025

Description

i changed entire logic of queue class and rewrote it using liked list to achieve O(1) time complexity while also keeping the same space compeltxity

Fixes #462

Type of change

  • New feature and entire logic rebust

Checklist:

  • [O] My code follows the style guidelines of this project i.e. Pep8
  • [O] I have performed a self-review of my own code
  • [O] I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • [dont know] Any dependent changes have been merged and published in downstream modules
  • I have squashed unnecessary commits

Copy link

@Himaanshuraikwar Himaanshuraikwar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

class Queue:
class __Node:
"""Private node class for the linked list logic."""
def init(self, element, next_node=None):
self.ele = element
self.next = next_node

def __init__(self):
    self.head = None  # Points to the front (where we dequeue)
    self.tail = None  # Points to the end (where we enqueue)
    self.length = 0

def is_empty(self):
    return self.length == 0

def put(self, item):
    """Add item to the end of the queue (Enqueue)."""
    new_node = self.__Node(item)
    
    if self.is_empty():
        self.head = new_node
        self.tail = new_node
    else:
        # Link the old tail to the new node, then move tail pointer
        self.tail.next = new_node
        self.tail = new_node
    
    self.length += 1

def get(self):
    """Remove and return the item from the front (Dequeue)."""
    if self.is_empty():
        return None
    
    # Capture the data from the head
    dequeued_item = self.head.ele
    # Move the head pointer to the next node
    self.head = self.head.next
    
    # If the queue is now empty, reset tail to None
    if self.head is None:
        self.tail = None
        
    self.length -= 1
    return dequeued_item

def rotate(self, rotation):
    """Moves the front element to the back 'n' times."""
    if self.is_empty():
        return
    for _ in range(rotation):
        self.put(self.get())

def size(self):
    return self.length

def __len__(self):
    return self.length

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Queue.get() logic is slow and unnecessary

3 participants