您可以返回将按字母顺序添加列表的单词的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)<0){
pNew =createWordCounter(word);
pLast->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);
关于c - 在C中按字母顺序添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23241760/