[英]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
This is what I have right now but it only prints out the first node.这就是我现在拥有的,但它只打印出第一个节点。 Thanks in advance.
提前致谢。
You can try something like你可以尝试类似的东西
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.