在C中添加节点字母

你可以返回addWord部分,它将按字母顺序添加单词吗?我试过但它没有用。我是C编程的新手。实际上,我正在研究它一周但我不能解决问题。

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; } 

我尝试了这部分,但它没有返回结果。这是

 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)pNext = pNew ; pNew->pNext = pCounter; pCounter = pLast->pNext; } else{ pNew=createWordCounter(word); pNew->pNext=pCounter; pLast->pNext=pNew; } } 

更新:

试试这个

 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);