0

Linked list remove

Been working a bit with linked list data structures, but I’m having a hard time with fully removing nodes from the list. I’m looking for the functionality similar to the remove function with lists where it not only makes the selected item a None but also completely removes the item and shifts the list as well. So far I can just set the data I’m looking to remove to None. https://code.sololearn.com/cev4J6nM8EnF/?ref=app

27th Dec 2021, 6:03 PM
Luke Simmons
2 odpowiedzi
+ 1
you could use the .pop() list method. It takes the index to remove as an optional parameter, defaults to -1. The method removes and returns the index given of the list a = ['a', 'b', 'c'] value = a.pop(0) print(a) # ['b', 'c'] print(value) # a
27th Dec 2021, 6:43 PM
Slick
Slick - avatar
0
In the linked list, each node points to the next one. So if you have 3 nodes like A -> B -> C And you want to remove B, then what you really need to do, is link A to C so it will look like this: A -> C So to do that, you actually need to find the element that links to the node you want to remove! Think also about the edge cases: - if there is only a single element in the list and you want to remove that (set head to None) - if you remove the last element, that should work out fine because the last-but-one element will end up pointing to None node - if the list is empty or the value you want to remove doesn't exist in the list, maybe you want to raise an error The removed node will eventually be garbage collected, as soon as no more other node refers to it. You are also tracking the size of the list in a separate variable, but you forget to decrement it on removal.
28th Dec 2021, 7:09 AM
Tibor Santa
Tibor Santa - avatar