I'm having a difficult time trying to create a function in a queue class to remove a certain node with the argument being the value of the node.
class LinkedQ:
def __init__(self):
self._first = None
self._last = None
def enqueue(self,x):
ny = Node(x)
if self._first == None:
self._first = ny
self._last = ny
else:
self._last.next = ny
self._last = ny
def remove(self,x):
current_node = self._first
while x != current_node.data: #Node(x):
last_node = current_node
current_node = current_node.next
if current_node == Node(x):
last_node.next = current_node.next
return
def display(self):
if self._first == None:
return None
else:
elements = []
current_node = self._first
elements.append(current_node.data)
while current_node.next != None:
current_node = current_node.next
elements.append(current_node.data)
print(elements)
class Node:
def __init__(self, x, next = None):
self.data = x
self.next = next
p = LinkedQ()
p.enqueue(1)
p.enqueue(2)
p.enqueue(3)
p.enqueue(4)
p.enqueue(5)
p.display()
p.remove(3)
p.display()
So it's the function def remove(self,x)
that I can't seem to get working. As it is right now I don't get an error message, but the output, using the def display(self):
, is still the same:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
meaning that the selected node hasn't been removed. Could somebody please tell me what I'm doing wrong? And how can I try to solve it instead? As you can see, I'm trying to solve it by changing the pointer of the previous node to point at the node that is located after our current node, making it disappear when nothing is pointing at it. That's how we are required to solve it.
PS. There are other functions in the code, such as enqueue()
and isEmpty()
but those aren't relevant in this case, they work properly as of now.