Thursday, December 7, 2023
HomeSoftware EngineeringConvert a LinkedList to a String in Python

# Convert a LinkedList to a String in Python

## The problem#

Preloaded for you is a category, struct, or derived knowledge sort `Node` (relying on the language) used to assemble linked lists on this problem:

``````class Node():
def __init__(self, knowledge, subsequent = None):
self.knowledge = knowledge
self.subsequent = subsequent
``````

Create a perform `stringify` which accepts an argument `listing`/`\$listing` and returns a string illustration of the listing. The string illustration of the listing begins with the worth of the present `Node`, specified by its `knowledge`/`\$knowledge`/`Information` property, adopted by a whitespace character, an arrow, and one other whitespace character (`" -> "`), adopted by the remainder of the listing. The top of the string illustration of a listing should at all times finish with `None`. For instance, given the next listing:

``````Node(1, Node(2, Node(3)))
``````

… its string illustration could be:

``````"1 -> 2 -> 3 -> None"
``````

And given the next linked listing:

``````Node(0, Node(1, Node(4, Node(9, Node(16)))))
``````

… its string illustration could be:

``````"0 -> 1 -> 4 -> 9 -> 16 -> None"
``````

Word that `None` itself can also be thought of a legitimate linked listing. In that case, its string illustration would merely be `"None"` (once more, relying on the language).

## The answer in Python code#

Choice 1:

``````Node.__str__ = lambda self: "%s -> %s" % (self.knowledge, self.subsequent)
stringify = str
``````

Choice 2:

``````def stringify(ll):
r = []
whereas ll:
r, ll = r + [str(ll.data)], ll.subsequent
return ' -> '.be part of(r + ['None'])
``````

Choice 3:

``````class Node():
def __init__(self, knowledge, subsequent = None):
self.knowledge = knowledge
self.subsequent = subsequent

def stringify(node):
ok = ''
whereas True:
if node == None:
ok += 'None'
return ok
else:
ok += '{} -> '.format(node.knowledge)
node = node.subsequent
``````

## Take a look at circumstances to validate our answer#

``````check.describe("stringify()")

check.it("ought to cross the instance exams as proven within the Description")
check.assert_equals(stringify(Node(0, Node(1, Node(2, Node(3))))), '0 -> 1 -> 2 -> 3 -> None')
check.assert_equals(stringify(None), 'None')
check.assert_equals(stringify(Node(0, Node(1, Node(4, Node(9, Node(16)))))), '0 -> 1 -> 4 -> 9 -> 16 -> None')
``````
RELATED ARTICLES