-1

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()

1 Answers1

0

Looking at your code, I think you need to change

if node % 2 == 0:

to

if node.data % 2 == 0:

Right now, you are just checking if the node itself is divisible by two, but you should be checking if the data is divisible by 2. Hope that helps.

Hawkeye312
  • 63
  • 1
  • 2
  • 9