-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()
5
  • 1
    Read What makes something iterable? to see how to make your LinkedList class iterable, but keep in mind that the remove_odd function will return a list of ints and not a LinkedList. Commented Jun 10, 2018 at 13:16
  • Possible duplicate of Build a Basic Python Iterator Commented Jun 10, 2018 at 13:20
  • I edited the code it gave me another error at the % operator Commented Jun 10, 2018 at 13:28
  • no, it's not a duplicate I've checked @ndmeiri Commented Jun 10, 2018 at 13:40
  • It was before you edited the question. Commented Jun 10, 2018 at 13:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.