简体   繁体   English

迭代/递归创建链表

[英]Iteratively/Recursively create a linked list

Need to recursively or iteratively create a linked list for a given number string.需要递归或迭代地为给定的数字字符串创建一个链表。

For example: Number = "123" 1 -> 2 -> 3例如:数字 = "123" 1 -> 2 -> 3

I wrote a recursive function but doesn't seem to work, it is creating a linked list but without the middle values.我写了一个递归 function 但似乎不起作用,它正在创建一个链表但没有中间值。 1 -> 3 instead of 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

This is the original use case这是原始用例

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

  • Your recursive approach looks correct.您的递归方法看起来是正确的。 Only thing you need to do is.你唯一需要做的就是。 you don't need to return head when you reach end of number.当您到达数字末尾时,您不需要返回头部。 Because you are already storing head in head variable.因为您已经将 head 存储在 head 变量中。
  • Here is code that works.这是有效的代码。
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

n = "1234"
def create_linked_list(head, num):
    if num is "": #base condition.
        return
    else:
        head.next = ListNode(num[0])
        create_linked_list(head.next, num[1:])

head = ListNode(n[0])
temp = head
create_linked_list(head, n[1:])

while temp:
    print(temp.val)
    temp = temp.next
  • Output Output

    1 1
    2 2
    3 3
    4 4

  • You can also rewrite above code as following.你也可以重写上面的代码如下。

def create_linked_list(head, num):
    if num is not "":
        head.next = ListNode(num[0])
        create_linked_list(head.next, num[1:])
  • PS : Remember to always back up your head when working with Linked Lists. PS :记住在使用链接列表时要始终保持头脑清醒。

Recursion is a functional heritage and so writing our program in functional style yields the best results.递归是一种函数式遗产,因此以函数式风格编写我们的程序会产生最好的结果。 This means we avoid things like mutating the list nodes, head.next =... .这意味着我们避免了诸如改变列表节点head.next =...之类的事情。 Your constructor should be able to set both val and next -您的构造函数应该能够同时设置valnext -

class node:
  def __init__(self, val, next = None):
    self.val = val
    self.next = next

def create_llist(v = None, *vals):
  if not v:
    return None
  else:
    return node(v, create_llist(*vals))

def llist_to_str(l = None):
  if not l:
    return "None"
  else:
    return f"{l.val} -> {llist_to_str(l.next)}"

print(llist_to_str(create_llist(1, 2, 3)))
# 1 -> 2 -> 3 -> None

But create_llist and llist_to_str would probably be more consistent if we implemented them as part of the class.但是如果我们将create_llistllist_to_str实现为 class 的一部分,它们可能会更加一致。 And maybe a better name is llist , for "linked list" -也许一个更好的名字是llist ,用于“链表” -

class llist:
  def __init__(self, val, next = None):
    self.val = val
    self.next = next

  def create(v = None, *more):
    if not v:
      return None
    else:
      return llist(v, llist.create(*more))

  def __str__(self):
    return f"{self.val} -> {self.next}"

print(llist.create(1, 2, 3))
# 1 -> 2 -> 3 -> None

Instead of relying on side effects, functions take inputs and produce an output.函数不依赖副作用,而是接受输入并生成 output。 As a result, notice how we our mind is free of complexity -结果,请注意我们的思想如何摆脱复杂性-

class llist:
  # ...
  def map(node = None, f = lambda x: x):
    if not node:
      return None
    else:
      return llist(f(node.val), llist.map(node.next, f))

print(llist.map(llist.create(7, 8, 9), lambda x: x * x))
# 49 -> 64 -> 81 -> None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM