A connected list is given, which is implemented as a tuple (a number, link to the following pair) of the form in which the values are already sorted: x = (1, (3, (4, (7, (9, None) It is necessary to implement a function that reverses the list: example of a call: reverse((1, (3, (6, (8, None))))) Result: (8, (6, (3, (1, None))))
This is what i've done, i know it's incorrect cause first element would be doubled then
def reverse(linked_list: tuple):
last_pair = (linked_list[0], None)
while linked_list[1]:
new_list = (linked_list[0], last_pair)
return new_list
return reverse(linked_list[1])
This is the result: (1, (1, None))
I have no idea how to do it in correct way, there is nothing about linked lists as tuples on the internet
CodePudding user response:
The implementation in the question does not evaluate all parts of the argument passed to reverse().
Here's one way to achieve your objective:
def reverse(t):
result = None
while True:
a, b = t
result = a, result
if (t := b) is None:
break
return result
print(reverse((1, (3, (6, (8, None))))))
Output:
(8, (6, (3, (1, None))))
CodePudding user response:
If you supply an additional argument for "reverse" sequence you can also succeed with recursive function:
def reverse(linked_t: tuple, rev_seq=None):
while linked_t[1] is not None:
rev_seq = (linked_t[0], rev_seq)
return reverse(linked_t[1], rev_seq)
else:
return linked_t[0], rev_seq
print(reverse((1, (3, (6, (8, None))))))
(8, (6, (3, (1, None))))