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!
时间: 2024-02-29 20:53:14 浏览: 152
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.
阅读全文