The following code inserts a node after an existing node in a singly linked list. The diagram shows how it works. Inserting a node before an existing one cannot be done directly; instead, one must keep track of the previous node and insert a node after it.
function insertAfter(Node node, Node newNode) // insert newNode after node newNode.next := node.next node.next := newNode
Inserting at the beginning of the list requires a separate function. This requires updating firstNode.