-3

I am currently learning linked lists in Python and solving such a task

Given a linked list's head, reverse it and return the head of the reversed list.

class Node:
    def __init__(self, link=None, val=None):
        self.val = val
        self.next = link

def reverseLL(head):
    reversed_head = Node()

    ### MY CODE
    reversed_head.val = head.next.val
    reversed_head.next = head
    ###
    return reversed_head

node2 = Node(None, 5)
node1 = Node(node2, 2)

# check that your code works correctly on provided example
assert reverseLL(node1) == Node(node1, 5), 'Wrong answer'

When I'm trying the function locally, I just get the wrong answer. But when I run the code via some online grader check, it outputs:

  RuntimeErrorElement(RuntimeError,Error on line 12:
    reversed_head.val = head.next.val
AttributeError: 'NoneType' object has no attribute 'next'

As I understand in this task I just need to assign the head's value for reversed_head and the same for link. What am I doing wrong?

martineau
  • 119,623
  • 25
  • 170
  • 301
evggenn
  • 23
  • 4
  • 2
    The script you provided shows no attempt. The error message mentions a line of code that is not in that snippet. Please provide code to reproduce the issue. Also, there are *lots* of questions and answers on this site about reversing a linked list. Show your research efforts. – trincot Jun 03 '22 at 11:59
  • If you want to reverse a linked list, you would have to go through all the elements of that list. As your code is currently written, you don't even look at more than two elements of the list (`head`, and `head.next`). In addition, even if you would only want to reverse 2-elements lists - your code doesn't do that. Your reversed list's head is linked to the input list's head, making it a 3-element list. Please plot out your solution, understand what it is you're trying to achieve. Good luck! – Itai Dagan Jun 03 '22 at 12:01

1 Answers1

1

Without regarding how you reverse a list, I can ensure you that your assert will always fail. Why ?

Consider this post Where is the default behavior for object equality (`==`) defined?

To sum it up, when you define a class, the operator == between two of its instances node_a and node_b will roughly performs a node_a is node_b. is compares the address of the objects, not their values.

Hence, since you are not overriding the default __eq__, a comparison between two Nodes performs an is.

Now in your assert, you compare the result of your function with a freshly created Node(node1, 5). In any case, those objects are two different entities that may share the same values. But being different entities, a is operation on them will always evaluate to false.

vultkayn
  • 189
  • 1
  • 8