Python linked contact list

I am trying to link a Python linked list without copying the data contained in the list nodes. I have a function that combines a list using copies of the nodes that were passed, but I cannot get a function that does not use copies to work.

These functions are intended for testing and synchronization purposes; I know the Python built-in list is awesome!

Here is the class I worked with and the concatenate function.

class Cell: def __init__( self, data, next = None ): self.data = data self.next = next def print_list(self): node = self while node != None: print node.data node = node.next 

The concatenation function must not be a member function of the Cell class.

 def list_concat(A, B): while A.next != None: A = A.next A.next = B return A 

This function overwrites the first element of the list if parameter A has more than one node. I understand why this is happening, but I'm not sure how to fix it.

Here is the testing code I used for this function.

 e = Cell(5) test = Cell(3, Cell(4)) test2 = list_concat(test2, e) test2.print_list() 

It would be helpful to get any information or help.

* edited to fix code formatting

+4
source share
2 answers

Try this instead:

 def list_concat(A, B): current = A while current.next != None: current = current.next current.next = B return A 

Assigning new values ​​to function parameters is bad programming practice, and the code in your question shows why: you used A to iterate over the original list, and thus you lost the link to your first element.

+5
source

I'm not sure if extend executes a copy or not, but in case it's not, just use

 A.extend(B) 
0
source

Source: https://habr.com/ru/post/1392502/


All Articles