[英]How to recursively convert an array to a linked list without using a loop? For python
def array_to_list_recursive(data):
i = 0
if len(data) == 0:
return None
else:
head = ListNode(data[i])
if i <= len(data):
i += 1
return head
這就是我現在擁有的,但它只打印出第一個節點。 提前致謝。
你可以嘗試類似的東西
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def print_node(self):
current = self
print(current.val, '-->', end='')
current = current.next
while(current):
print(current.val, '-->', end='')
current = current.next
l = [1, 5, 3, 7]
assert(len(l) > 0)
def produce_ll(l, head=None, current=None, index=0):
if(index > len(l)-1):
return head
if(head == None):
head = Node(l[index])
current = head
return produce_ll(l, head, current, index+1)
next_node = Node(l[index])
current.next = next_node
current = next_node
index += 1
return produce_ll(l, head, current, index)
head = produce_ll(l)
print(head.print_node())
1 -->5 -->3 -->7 -->None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.