我在這里看到了很多類似的問題,但都沒有涉及我想知道的問題。讓我們舉個例子吧。
我想從一個陣列制作一個鏈接串列。忽略所有的模板,讓我們進入這個問題的核心。
arr = [1, 2, 3, 4, 5]
tail = head = None # 這是有問題的一行。
for item in arr:
tail = Node(val=item, next=None)
tail = tail.next None
return head
不用說,這并不奏效。Head總是指向None,無論tails指向什么。
我還試過一些其他的東西:
head = tail = [] # head會在完成后指向空串列。
head = tail = any_other_singleton # 不作業。
我知道為什么會發生這種情況。它是因為我正在重新分配tail以指向一個Node。但是我想在'head'中保留對喜歡的串列的頭部的參考。我怎樣才能使其發揮作用?在其他編程語言中,這很簡單,但在python中,你必須在宣告時給變數賦值,這給我帶來了問題。
uj5u.com熱心網友回復:
只需單獨處理第一項。
arr = [1, 2, 3, 4, 5]
head = tail = Node(val=arr[0], next=None)
for item in arr[1:] 。
tail.next = Node(val=item, next=none)
tail = tail.next
return head
uj5u.com熱心網友回復:
可以使用一個假的before真正的串列。如果arr是空的,它就不會崩潰。
arr = [1, 2, 3, 4, 5]
tail = dummy = Node(val=None, next=None)
for val in arr:
tail.next = tail = Node(val=val, next=None)
return dummy.next
由于缺少Node類,所以沒有測驗。
uj5u.com熱心網友回復:
你想達到的目的可能可以這樣做。
你想達到的目的可能可以這樣做。
from collections import namedtuple
Node = namedtuple('Node'/span>, ['val'/span>, 'next'/span>])
def array_to_list(arr) 。
lst = None。
for a in reversed(arr)。
lst = Node(val=a, next=lst)
return lst
x = array_to_list([1, 2, 3] )
print(x)
接下來的代碼可能有助于理解,如果你從未處理過持久性(不可變)資料結構:
def insert_recursive(lst, pos, value)。
if not pos or not lst:
return Node(val=value, next=lst)
return Node(val=lst.val, next=insert_recursive(lst.next, pos - 1, value)
def insert_nonrecursive(lst, pos, value) 。
值 = []
while lst and pos:
values.append(lst.val)
lst = lst.next[/span]。
pos -=1
result = Node(val=value, next=lst)
while len(values)。
result = Node(val=values.pop(), next=result)
return result
y = insert_recursive(x, 1, 42)
print(y)
z = insert_nonrecursive(x, 1, 42)
print(z)
uj5u.com熱心網友回復:
我知道functools.reduce在Python世界中是一個黑羊,但是如果你對串列進行反向處理,它就會成為一個不錯的單行代碼。例如:
from functools import reduce
from collections import namedtuple
Node = namedtuple('Node', ['next', 'val']) # 或者是一個具有next, val成員的類。
arr = [ 1, 2, 3, 4, 5]
# Make Linked Listreversed(arr), None)
# 嘗試列印它們。
head = lst
while head:
print(head.val)
head = head.next(head.val)
將列印:
1
2
3
4 4
5 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315444.html
標籤:
上一篇:可以啟動行程,最小化視窗,點擊打開同一個視窗行程嗎?[復制]
下一篇:向函式傳遞結構指標陣列
