educative.io

Doubt about insert after node

Hi there,
I’m confused about this part:
def insert_after_node(self, prev_node, data):
** if not prev_node:**
** print(“Previous node does not exist.”)**
** return**
We haven’t defined prev_node before, it’s just an input. Why we can directly write “if not prev_node” here? And I’m not sure if I understand it in a right way. Whether the code here is for checking our input prev_node is in the linked list or the linked list is empty or not.

Thank you very much!

Hello @larryubc

prev_node is just the reference to the node after which we want to insert our new node. It should be noted that we are passing prev_node as an argument to the function insert_after_node. So we do not need to define it anywhere. It could be named anything. It is just a function argument or parameter. We are passing this parameter at line 49 of the code snippet i.e. llist.insert_after_node(llist.head.next, "D"). Hence, llist.head.next is our prev_node in this case.

Furthermore, “if not prev_node” is just a base condition. For instance if null is passed, then there would be no prev_node so we need to check for this scenario. So this piece of code is checking whether our input prev_node is in the list or not.

Hope this helps!

It helps a lot! Thank you so much!