I will try to explain with a simple example.
Given a list of data elements ['B', 'D', 'E]
let's create a Linked List consisting of Nodes each Node will be defined by 3 pieces of info as follows:
- id - just a number representing the sequence of node instantiation
- data - the data contained within the node
- prev_node - the node id of the previous node
Given this data let's build a linked list using your add method:
LL = LinkedList() -> LL.self.head = None
LL.add_beg('B') -> Node(1, 'B', None), LL.self.head = 1
When we execute LL.add_beg('B') we create a Node instance and set LL.self.head = node Id
When we add a second data value
LL.add_beg('D') -> Node(2, 'D', 1), LL.self.head = 2
At this point we have the following:
LL.self.head = 2
Node(2, 'D', 1)
Node(1, 'B', None)
Now let's add a Node between 2 & 1, as folows:
LL.add_after(2, 'E')
new_node = Node('E') -> Node(3,'E', None)
new_node.pointer= prev_node.pointer -> Node(3, 'E', 1) From the prev_pointer of Node #2
prev_node.pointer=new_node -> Node(2, 'D', 3) update Node #2 with new_node ID
The end result is a linkedList that lookslike the following:
LL.self.head = 2
Node(2, 'D', 3)
Node(3, 'E', 1
Node(1, 'B', None)
And the new node is successfully inserted between Nodes 1 & 2.