[英]Faster way to create a linked list of n-length in Python
我正在尝试使用Python创建长度为n的链表。 我实现了简单的列表,有一个有效的串联函数和一个有效的create_list函数; 但是,我只想知道是否有比使用我的串联函数(用于测试)更有效的方法来创建链表。
简单列表类:
class Cell:
def __init__( self, data, next = None ):
self.data = data
self.next = next
串联功能:
def list_concat(A, B):
current = A
while current.next != None:
current = current.next
current.next = B
return A
列出创建(这将永远!):
def create_list(n):
a = cell.Cell(0)
for i in (range(1,n)):
b = cell.Cell(i)
new_list = cell.list_concat(a, b)
return new_list
改进代码的最简单方法是:
def create_list(n):
new_list = cell.Cell(0)
last_a = new_list
for i in (range(1,n)):
a = cell.Cell(i)
cell.list_concat(last_a, a)
last_a = a
return new_list
这将使方法的复杂度从O(n ** 2)降至O(n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.