Convert a LinkedList to a String in Python

The challenge

Preloaded for you is a class, struct, or derived data type Node (depending on the language) used to construct linked lists in this challenge:

class Node(): def __init__(self, data, next = None): self.data = data self.next = next
Code language: Python (python)

Create a function stringify which accepts an argument list/$list and returns a string representation of the list. The string representation of the list starts with the value of the current Node, specified by its data/$data/Data property, followed by a whitespace character, an arrow, and another whitespace character (" -> "), followed by the rest of the list. The end of the string representation of a list must always end with None. For example, given the following list:

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

… its string representation would be:

"1 -> 2 -> 3 -> None"
Code language: JSON / JSON with Comments (json)

And given the following linked list:

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

… its string representation would be:

"0 -> 1 -> 4 -> 9 -> 16 -> None"
Code language: JSON / JSON with Comments (json)

Note that None itself is also considered a valid linked list. In that case, its string representation would simply be "None" (again, depending on the language).

The solution in Python code

Option 1:

Node.__str__ = lambda self: "%s -> %s" % (self.data, self.next) stringify = str
Code language: Python (python)

Option 2:

def stringify(ll): r = [] while ll: r, ll = r + [str(ll.data)], ll.next return ' -> '.join(r + ['None'])
Code language: Python (python)

Option 3:

class Node(): def __init__(self, data, next = None): self.data = data self.next = next def stringify(node): k = '' while True: if node == None: k += 'None' return k else: k += '{} -> '.format(node.data) node = node.next
Code language: Python (python)

Test cases to validate our solution

test.describe("stringify()") test.it("should pass the example tests as shown in the Description") test.assert_equals(stringify(Node(0, Node(1, Node(2, Node(3))))), '0 -> 1 -> 2 -> 3 -> None') test.assert_equals(stringify(None), 'None') test.assert_equals(stringify(Node(0, Node(1, Node(4, Node(9, Node(16)))))), '0 -> 1 -> 4 -> 9 -> 16 -> None')
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments