shanehowe
shanehowe

Reputation: 45

Python Queue class.. trouble understanding enqueue method

So I am trying to learn data structures in python and have moved on to trying to implement a queue. I understand how the data structure works. However I am now defining the enqueue method.

I am learning this on Codecademy btw.

The queue class looks like this:

from node import Node

class Queue:
  def __init__(self, max_size=None):
    self.head = None
    self.tail = None
    self.max_size = max_size
    self.size = 0
    
  # Add your enqueue method below:
  def enqueue(self, value):
    if self.has_space():
      item_to_add = Node(value)
      print("Adding " + str(item_to_add.get_value()) + " to the queue!")
    
      if self.is_empty():
        self.head = item_to_add
        self.tail = item_to_add
      else:
        self.tail.set_next_node(item_to_add)
        self.tail = item_to_add
    
      self.size += 1
    else:
      print("Sorry, no more room!")
    
  def peek(self):
    if self.is_empty():
      print("Nothing to see here!")
    else:
      return self.head.get_value()
  
  def get_size(self):
    return self.size
  
  def has_space(self):
    if self.max_size == None:
      return True
    else:
      return self.max_size > self.get_size()
    
  def is_empty(self):
    return self.size == 0

The node class looks like this

class Node:
  def __init__(self, value, next_node=None):
    self.value = value
    self.next_node = next_node
    
  def set_next_node(self, next_node):
    self.next_node = next_node
    
  def get_next_node(self):
    return self.next_node
  
  def get_value(self):
    return self.value

What I have trouble understanding is the enqueue method specifically this part:

self.tail.set_next_node(item_to_add)
self.tail = item_to_add

Why am I setting the tails next node the the node I am adding to the queue? From what I gather I should set the item_to_add 's next node to be the current tail and then I should say self.tail_node is now the item_to_add?

Any help greatly appreciated as I am quite new to the data_structures and algorithms aspect of things.

Upvotes: 0

Views: 485

Answers (1)

Varun Pius Rodrigues
Varun Pius Rodrigues

Reputation: 347

When you enqueue, you are appending the node to the end. In the example you have stated, the queue's current last node is tail (accessed via self.tail)

When you enqueue to this queue, the current tail becomes the second to last node rather than the last. Hence, we do self.tail.set_next_node(item_to_add). This is because the current last node (i.e the tail)'s next reference is Null. You update it to the item_to_add, which will be the new last node and then change self.tail to item_to_add to indicate this is the new tail/last node.

Upvotes: 1

Related Questions