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
The simplest way to improve your code is this:
This will bring the complexity of the approach down to O(n) from O(n**2).