1

I am trying to count the numbers of nodes in a linked list when the node value is a non-negative odd, but it seems that I couldn't get the right result.

class Solution:
    """
    @param head: 
    @return: nothing
    """
    def countNodesII(self, head):
        count = 0
        while head.next is not None:
            head = head.next
            if head.val > 0 and head.val % 2 != 0:
                count += 1 
            else:
                return 0
        return count

if the input is 1->3->5->null I expect to get result of 3, but my program returned 2 instead.

0

1 Answer 1

2

Some issues in your code

  • You would want to move to next node via head=head.next after you check the head node for the condition, right now you are skipping head

  • You would want to remove return from else, and only return count at the end

  • You want to check if head reaches None since you are using it to iterate over your list

So the updated code will look like

class Solution:
    """
    @param head: 
    @return: nothing
    """
    def countNodesII(self, head):
        count = 0
        #Iterate over the list
        while head != None:
            #Check for condition
            if head.val > 0 and head.val % 2 != 0:
                count += 1
            #Move to next node
            head = head.next
        return count
Sign up to request clarification or add additional context in comments.

3 Comments

Exactly this :D
That this is the exact and simplest solution ;)
Thanks, it's really helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.