I’m trying to understand this code from Deitels 5th edition c book.
If I’m an inserting a new node in a linked list, why am I setting a nextPtr = *sPtr. Shouldn’t the first node have a nextPtr of NULL?
Also what does *sPtr = newPtr mean?
struct listNode {
char data;
struct listNode *nextPtr;
};
void insert(ListNodePtr *sPtr, char value)
{
ListNodePtr newPtr; /* pointer to a new node */
ListNodePtr previousPtr; /* pointer to a previous a node in list */
ListNodePtr currentPtr; /* pointer to current node in list */
newPtr = malloc(sizeof(ListNode)); /* create node */
if (newPtr != NULL){ /* is space available */
newPtr->data = value;
newPtr->nextPtr = NULL;
previousPtr = NULL;
currentPtr = *sPtr;
while (currentPtr != NULL && value > currentPtr->data){
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
/* insert new node at beginning of list */
if (previousPtr == NULL){
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
} else { /* insert new node between previosuPtr and currentPtr */
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
}
The first node shouldn’t have it’s
nextPtrset toNULL, that would be the last node (afterall you need to be able to get from the first to the second node). ThenextPtrof the first node points to the second node, which has a pointer to the third node and so on. So when you insert at the beginning of the list you let thenextPtrof the new node point to the old beginning of the list, which is*sPtr. Afterwards you set the pointer which points to the beginning of the list to point to the new node by doing*sPtr=newPtr.