user10626361
user10626361

Reputation: 25

printing linked list with pointers with python

Im a python beginner and trying to create a function the prints out the values of a linked list with a pointer '->' I created a solution, but it appears its failing on of my testers, and idk why.

class LinkNode:
def __init__(self,value,nxt=None):
    assert isinstance(nxt, LinkNode) or nxt is None
    self.value = value
    self.next = nxt

def print_list(lst):
    """
    >>> print_list(LinkNode(3, None))
    3 -> None
    """
    temp = lst
    while temp:
       print(temp.value, sep = '', end=' -> ')
       temp = temp.next

Everytime i run it it creates the same output, and looks the same but there is an error saying:

 Test Failed: '3 -> ' != '3 -> None\n'
 - 3 -> 
 + 3 -> None

Im not sure what the \n is trying to say?

Upvotes: 1

Views: 86

Answers (1)

gilch
gilch

Reputation: 11691

The \n is the escape code for a "new line".

The sep argument doesn't do anything unless you print more than one item in the same print call.

You also aren't printing the final None. Do so after the while loop.

def print_list(lst):
    """
    >>> print_list(LinkNode(3, None))
    3 -> None
    """
    temp = lst
    while temp:
       print(temp.value, end=' -> ')  # you don't need sep here.
       temp = temp.next
    print(temp)

Upvotes: 1

Related Questions