Skip to content
Advertisement

Insert an item at the begining of linked list by Python3

How to modify the following code? so that the item can be inserted to the begining of a linked list with add()? why None shows up at the beginning of the linked list? is there anything wrong? I tried several times. It just does not work. What heppened? Any suggestions to change? Is ther any good suggestion when writing a linked list?

JavaScript

Why there is no 999 and How to remove None at the begining?

Advertisement

Answer

Since the Linked List is created with a dummy node as head, and all other methods depend on that assumption, add should never replace it. The idea behind this dummy node, is that it will always be there and never change. It helps to keep code simple (at the cost of the memory for one extra node).

So avoid that add changes the head attribute. The new node should be inserted just after that head:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement