0

Given a list in C:

struct listNode
{  
    int val;
    struct listNode *nextPtr;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

If, in the process of inserting a new item in a list given by a pointer to the last item (*sPtr), so a new node, I want to modify the pointer *sPtr make it point to the new node, and then make the new node the last one, it is right to write this like below?

ListNodePtr newPtr;    
newPtr=malloc(sizeof(ListNode));
if(newPtr!=NULL)
{
    newPtr->val=whatever;
    newPtr->nextPtr=NULL;
    *sPtr->nextPtr=newPtr;
    *sPtr=*sPtr->nextPtr;
} 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
HaroldF
  • 105
  • 4

1 Answers1

0

You must check if the last item (sPtr) is null or not before dereferencing it because list is empty at first (assuming dummy root node is not used)

Also you could set last item like this *sPtr = newPtr instead of *sPtr = *sPtr->nextPtr. Next pointer is newPtr so assigning it to newPtr would make things more clear and less error-prone

Updated version would be:

ListNodePtr newPtr;    
if((newPtr = malloc(sizeof(ListNode)))) {
  newPtr->val     = whatever;
  newPtr->nextPtr = NULL;

  if (*sPtr)
    (*sPtr)->nextPtr = newPtr;

  *sPtr = newPtr;
}
recp
  • 383
  • 1
  • 2
  • 14