I have a basic linked-list implementation in python. Each Cell has some data associated with it and a next object, used to include the rest of the linked list (and null if only the first param of data is given in the constructor).
I want to copy and concatenate two lists together, so that the final product preserves the order and is independent of the two original lists.
Here is what I have:
def list_concat_copy(A, B):
C = Cell(A)
while A.next != None:
A = A.next
C = Cell(A,C)
C = Cell(B,C)
while B.next != None:
B = B.next
C = Cell(B,C)
return C
The issue that I am having is that this reverses the order:
A = Cell(8,Cell(9,Cell(10)))
B = Cell(11,Cell(12,Cell(13)))
C = list_concat_copy(A,B)
Now if I walk_and_print(C) I get 13 12 11 10 9 8
Any thoughts?
You do some weird stuff:
suggests that your Cell is something like
but doing
never copies anything, it just creates a new Cell with the same A as a value.
So, lets start with a Cell that can actually copy itself:
Now your concat is easy:
For completeness, here is what your tried to do:
I think this helps to understand how you accidentally reversed your cells: You walked the list forwards but the
C = Cell(A,C)puts a new Cell before the oldC, so that builds the new list from the end.