I was doing Singly-Linked List implementation and I remember Linus Torvalds talking about it here.
In a singly-linked list in order to remove a node we should have access to the previous node and then change the node it is currently pointing to.
So any way we should have access to the previous node.
But Linus Torvalds removed the special case by using the idea of address in C. So that head also has the 'previous thing' which is the address of head which points to head. So he has used C's feature of pointer and address to remove special case.
The normal code with special case
The code with special case becoming normal case
I think this kind of special case removal in singly linked list cannot be done in python, because we don't have the concept of pointers (and hence I will not be able to go one step before head)? Am I right ?
My first thought upon reading your question was: why would you want to build a singly linked list in python? Python offers a wealth of collection types and you can use these without having to worry about whether they are implemented as singly linked list, as double linked list or as some non-recursive data structure (which are usually easier to handle).
But the answer to your question is: Python allows of course to build a singly linked list. For example, the following code does just that:
The difference to C is: we did not have to
malloc()
or work with pointers because python handles memory for us. Python has references instead of pointers, they are similar but much safer and easier to use.However, before implementing a linked list, you should consider what your requirements are regarding your collection and maybe you can pick a good one from the built-ins or from the collections module.