【发布时间】:2019-10-08 17:04:03
【问题描述】:
需要递归或迭代地为给定的数字字符串创建链表。
例如: 数字 = "123" 1 -> 2 -> 3
我写了一个递归函数但似乎不起作用,它正在创建一个链表但没有中间值。 1 -> 3 而不是 1 -> 2 -> 3
def create_linked_list(head, num):
if num is "":
return head
else:
head.next = ListNode(num[0])
return create_linked_list(head.next, num[1:])
n = "123"
head = ListNode(n[0])
result = create_linked_list(head, n[1:])
while result:
print(result.val)
head = result.next
# This is printing 1 -> 4
这是原始用例
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
n = "1234"
# I need this part of linked list creation to be done
# in a looping/recursive manner for any kind of number.
l1 = ListNode(n[0])
l1.next = ListNode(n[1])
l1.next.next = ListNode(n[2])
l1.next.next.next = ListNode(n[3])
while l1:
print(l1.val)
head = l1.next
# 1 -> 2 -> 3 -> 4
【问题讨论】:
-
这不是你的问题,但
if num is ""是个坏主意。考虑改用if not num或if len(num) == 0。 -
我认为
return create_linked_list(head.next, num[1:])应该是create_linked_list(head.next, num[1:]); return head -
返回 head 没有意义,因为它更新了,你不能用那个 head 遍历回来。在这种情况下,它的尾巴不是头。 (在单链表的情况下不留尾)
-
@Eric 在这里返回
head的目的是什么? -
你为什么要在 Python 中显式实现链表?
标签: python recursion linked-list