I'm attempting to create a linked list of length n using Python. I have the simple list implemented, a working concatenation function, and a working create_list function; however, I just want to know if there is a more efficient method at making the linked list than using my concatenate function (made for testing).
Simple List Class:
class Cell:
def __init__( self, data, next = None ):
self.data = data
self.next = next
Concatenate Function:
def list_concat(A, B):
current = A
while current.next != None:
current = current.next
current.next = B
return A
List create (that takes forever!):
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
This is an assignment, but efficiency is not part of it. I am just wondering if there is a more efficient way to create a large list using this implementation of the structure.
while current.next is not None
will suffice. Given thatCell
has no defined boolean truthness, it is as object "always True" and you could reduce the while loop towhile current.next
. – Elmer Jan 26 '12 at 14:50