Я думаю, что я заставил его работать.
Первое, что я изменил в вашем коде, это определение вашей структуры как typdef.
typedef struct{
char data[100];
struct listnode *nextPtr;
}listnode;
Это то, как я учился, и это делает егопроще объявить переменные этого типа структуры, так как мы можем просто вводить «listnode» вместо «struct listnode» все время.
Поскольку вы не дали нам полный код, мне пришлось удалить некоторые вещитак что я мог бы скомпилировать это.Поскольку вы просто спрашиваете, почему список остается пустым после функции «вставки», я думаю, что это хорошо для вас. Итак, вот функции «main ()» и «printlist ()», которые я использовал:
void printList(listnode *strPtr){
listnode *currentPtr = malloc(sizeof(listnode));
//Setting the ptr to run the list
currentPtr = strPtr;
if(strPtr == NULL) printf("Fail\n");
//Printing the list,while next is different than NULL keep going
printf("\nListing:\n");
while(currentPtr->data != NULL){
printf("%s\n",currentPtr->data);
currentPtr = currentPtr->nextPtr;
}
}
int main(){
char nume[128];
listnode *startPtr = NULL;//Initializing the fisrt ptr
//Reading the name
printf("Enter name:\n");
scanf("%s",nume);
//Inserting and printing the list
insert(&startPtr,nume);
insert(&startPtr,"Hello");
printList(startPtr);
return 0;
}
Некоторые довольно простые вещи.Теперь о главном:
Как сказали нам наши друзья в комментариях, в C указатель передается по значению.Это означает, что какие бы изменения вы ни делали в функции, она не изменит переменную startPtr в main ().Чтобы исправить это, ему нужно добавить еще один '*' к параметрам функции.Это означает, что теперь мы передаем аргумент strPtr по ссылке.
Вот последняя функция:
void insert(listnode **strPtr,char value[]){
listnode *previousPtr, *currentPtr,*newPtr;
//Allocating the nodes
newPtr = malloc(sizeof(listnode));
currentPtr = malloc(sizeof(listnode));
//Initializing the new node and setting the currentPtr
strcpy(newPtr->data,value);//Copying the name to the new node
newPtr->nextPtr = NULL;
currentPtr = strPtr;
//Previous is NULL
previousPtr = NULL;
if(newPtr != NULL){
//If there's already a node in the list let's find the right location
//For the new one(sorting)
while(currentPtr != NULL && strcmp(currentPtr->data,value) > 0){
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
//If previous is NULL than this is the first node,no while iterations
//Note:strPtr is passed by reference,extra '*' needed
if(previousPtr == NULL){
newPtr->nextPtr = *strPtr;
*strPtr = newPtr;
}else{
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
*strPtr = newPtr;
}
}else{
printf("%s was not inserted. Insuffiecient memory!",value);
}
}
Обратите внимание, что мы также используем дополнительный '*' при установке newPtr в strPtr.Это изменит фактическую переменную startPtr из main ().
Из этого, я надеюсь, вы также можете исправить функцию удаления!Не забудьте освободить память!Также не забывайте комментировать свой код.Очень важно помочь вам и другим людям понять это, как бы легко это ни было!
Ура!