Adding Nodes to a Linked List
Before we let Copilot create the code for us, let’s think about how this needs to work.
The following illustration shows what we need to happen in memory when we add our first element. This logic needs to allocate the space for the node, set its data, set its next to NULL, and then update it to be the first and last node in the list.
Adding more nodes
The logic for the 2nd node, and all subsequent nodes, will differ as we need to link it to the existing nodes in the list. We need to add the node after the list’s last
node.
The following illustration shows how we need to connect the new node in the list. The logic includes allocating space for the node, set its data, set its next to NULL
, update the last
node’s next
to refer to the new node, and then change which node is last
in the list.
The Code
Copilot has us covered for this. For me, Copilot generated the comment and the following code. Before we move on we need to make sure that this works as we want. Step through the code, and double check that things will work for the first and all subsequent nodes added to the list.