Insert a new node at the top of the Linked-List

In a simple C implementation of Linked List, I was unable to define a function string named insert (). It takes a char and adds to the linked list in alphabetical order. A line about creating a new node when the list is empty. And since there will be only one node in the list, the line should look like Ive commented out, am I mistaken?

/****************************************************/

void insert( ListNodePtr *sPtr, char value ){
ListNodePtr newPtr;    
ListNodePtr previousPtr;
ListNodePtr currentPtr;

newPtr = malloc( sizeof( ListNode) );

if( newPtr != NULL ){       //is space available
    newPtr->data = value;       //place value in node
    newPtr->nextPtr = NULL;      //node does not link to another node

    previousPtr = NULL;
    currentPtr = *sPtr;         //indirection to startPtr

    while( currentPtr != NULL && value > currentPtr->data ){
        previousPtr = currentPtr;               //walk to ...
        currentPtr = currentPtr->nextPtr;       //... next node
    }

    //insert new node at the beginning of the list
    if( previousPtr == NULL ){
        newPtr->nextPtr = *sPtr;            ///////////////////////////////////////////////  newPtr->nextPtr = NULL   ???
        *sPtr = newPtr;
    }
    else{           //insert new node between previousPtr and currentPtr
        previousPtr->nextPtr = newPtr;
        newPtr->nextPtr = currentPtr;
    }

}
else
    printf( "%c not inserted. No memory available.\n", value);
}//end-of insert

/*******************************************************/

typedef commands in main ():

typedef struct listNode ListNode;
typedef ListNode* ListNodePtr;

and the insert () function is called in main () as follows:

insert( &startPtr, item);

initialization startPointer in main ();

ListNodePtr startPtr = NULL;
+3
source share
2 answers

I think you forgot the case. The selected row will be called if

  • the list is empty
  • the character is smaller than all other characters in the list and should be inserted at the beginning of the list

To understand the second case, look at the code before:

while( currentPtr != NULL && value > currentPtr->data ){
    previousPtr = currentPtr;               //walk to ...
    currentPtr = currentPtr->nextPtr;       //... next node
}

value > currentPtr->data , previousPtr == NULL *sPtr != NULL ( , node ).

*sPtr NULL, NULL , .

+3

* sPtr . * sPtr Node , , NULL * sPtr. * sPtr NULL, .

:

if( previousPtr == NULL ){
        newPtr->nextPtr = NULL;
        *sPtr = newPtr;
    }

* sPtr = Node1, :

Node1->Node2->Node3

Node1

Ptr- > NULL * sPtr = newPtr

Node .

+1

Source: https://habr.com/ru/post/1796707/


All Articles