Write a function link_to_list that takes in a linked list and returns the sequence as a Python list. You may assume that the input list is shallow; none of the elements is another linked list. Try to find both an iterative and recursive solution for this problem!其中class Link: empty = () def init(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest def repr(self): if self.rest is not Link.empty: rest_repr = ', ' + repr(self.rest) else: rest_repr = '' return 'Link(' + repr(self.first) + rest_repr + ')' def str(self): string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>'
时间: 2024-02-29 12:53:32 浏览: 84
Sure! Here's an iterative solution for the function link_to_list:
```
def link_to_list_iter(link):
result = []
while link is not Link.empty:
result.append(link.first)
link = link.rest
return result
```
And here's a recursive solution:
```
def link_to_list_rec(link):
if link is Link.empty:
return []
else:
return [link.first] + link_to_list_rec(link.rest)
```
Both functions take a linked list as input and return it as a Python list. Hope this helps!
相关问题
Write a function link_to_list that takes in a linked list and returns the sequence as a Python list. You may assume that the input list is shallow; none of the elements is another linked list. Try to find both an iterative and recursive solution for this problem!
Iterative solution:
```python
def link_to_list(head):
lst = []
current = head
while current:
lst.append(current.val)
current = current.next
return lst
```
This solution traverses the linked list from the head node to the last node, appending the value of each node to a Python list. Once the end of the linked list is reached (i.e., the current node is `None`), the list is returned.
Recursive solution:
```python
def link_to_list(head):
if head is None:
return []
else:
return [head.val] + link_to_list(head.next)
```
This solution is a recursive implementation of the same logic. The base case is when the head node is `None`, in which case an empty list is returned. Otherwise, the function recursively calls itself on the next node in the linked list and appends the value of the current node to the resulting list. The final result is the concatenation of all these lists.
阅读全文