问题
Can you return addWord part which will add word the list alphabetically?i tried but it didn't work.I'm very new at C programming.Actually,i'm working on it since one week but i can not the problem.
typedef struct NODE {
char *str;
int count;
struct NODE *pNext;
} NODE;
void addWord(char *word)
{
NODE *pCounter = NULL;
NODE *pLast = NULL;
if(pStart == NULL) // pstart is globally defined pStart=NULL;
{
pStart = createWordCounter(word);
return;
}
/* If the word is in the list, increment its count */
pCounter = pStart;
while(pCounter != NULL)
{
if(strcmp(word, pCounter->str) == 0)
{
++pCounter->count;
return;
}
pLast = pCounter;
pCounter = pCounter->pNext;
}
/* Word is not in the list, add it */
pLast->pNext = createWord(word);
}
NODE* createWord(char *word)
{
NODE *pCounter = NULL;
pCounter = (NODE*)malloc(sizeof(NODE));
pCounter->str = (char*)malloc(strlen(word)+1);
strcpy(pCounter->str, word);
pCounter->count = 1;
pCounter->pNext = NULL;
return pCounter;
}
I tried this part but it didn't return the result.Here
void addWord(char *word)
{
NODE *pCounter = NULL;
NODE *pLast = NULL;
NODE *pNew = NULL;
if(pStart == NULL)
{
pStart = createWordCounter(word);
return;
}
/* If the word is in the list, increment its count */
pCounter = pStart;
while(pCounter != NULL)
{
if(strcmp(word, pCounter->str) == 0)
{
++pCounter->count;
return;
}
pLast = pCounter;
pCounter = pCounter->pNext;
}
while(pCounter != NULL){
if(strcmp(word,pCounter->str)<0){
pNew =createWordCounter(word);
pLast->pNext = pNew ;
pNew->pNext = pCounter;
pCounter = pLast->pNext;
}
else{
pNew=createWordCounter(word);
pNew->pNext=pCounter;
pLast->pNext=pNew;
}
}
回答1:
Updated:
Try this
while(pCounter != NULL)
{
if(strcmp(word, pCounter->str) == 0)
{
++pCounter->count;
return;
}
if(strcmp(word,pCounter->str)<0)
{
if (pCounter == pStart)
{
// TODO: insert at the begining
return;
}
else
{
pNew = createWordCounter(word);
pLast->pNext = pNew;
pNew->pNext = pCounter;
pCounter = pLast->pNext;
return;
}
}
pLast = pCounter;
pCounter = pCounter->pNext;
}
/* Word is not in the list, add it */
if (pLast == NULL)
{
// TODO: insert at the begining
}
else
pLast->pNext = createWord(word);
来源:https://stackoverflow.com/questions/23241760/add-node-alphabetical-in-c