I'm trying to remove all odds from a linked list, the method that I wrote works perfectly on lists but when applied to a linked list it breaks with an error:
TypeError: unsupported operand type(s) for %: 'Node' and 'int'
How can I solve it, my code looks like this:
class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
def print_list(self):
node = self.head
while node is not None:
print(node, end=' ')
node = node.next
print('')
def add_at_head(self, node):
node.next = self.head
self.head = node
self.length += 1
def remove_node_after(self, node):
if node.next is not None:
temp = node.next
node.next = node.next.next
temp.next = None
def remove_odd(l):
node = l.head
for i in range(l.length):
if node % 2 == 0:
LinkedList.remove_node_after(node)
node = node.next
else:
node = node.next
def main():
my_list = LinkedList()
my_list.add_at_head(Node(1))
my_list.add_at_head(Node(2))
my_list.add_at_head(Node(3))
remove_odd(my_list)
my_list.print_list()
main()