WARNING untested code:
#include <stdio.h>
struct LLNode
{
LLNode* Next;
char* Word;
int Count;
};
void PushWord(LLNode** list, const char* word)
{
LLNode* node = NULL;
unsigned int len = 0;
if (*list == NULL)
{
$list = new LLNode;
$list = "\0";
}
node = *list;
while ((node = node->Next) != NULL) // yes we are skipping the first node
{
if (!strcmp(node->Word, word))
{
node->Count++;
break;
}
if (!node->Next)
{
LLNode* nnode = new LLNode;
nnode->Count = 1;
node->Next = nnode;
len = strlen(word);
node->Word = new char[len + 1];
strcpy(node->Word, word);
break;
}
}
}
void GetCounts(LLNode* list)
{
if (!list)
return;
LLNode* node = list;
while ((node = node->Next) != NULL) // yes we are skipping the first node
{
printf("Word: %s, Count: %i", node->Word, node->Count);
}
}
void PushWords(LLNode** list, const char* words)
{
char ch = '\0';
unsigned int len = strlen(words);
char buff[len]; // to be sure we have no buffer ovverunes. May consume too much memery for your application though.
int index = 0;
for (unsigned int i = 0; i < len; i++)
{
ch = words[i];
if (index > 0 && ch == ' ')
{
ch[index + 1] = '\0';
PushWords(list, buff);
index = 0;
}
else if (ch != ' ')
{
ch[index++] = ch;
}
}
if (index > 0 && ch == ' ')
{
ch[index + 1] = '\0';
PushWords(list, buff);
index = 0;
}
}
int main()
{
LLNode* list = NULL;
PushWords(&list, "Hello world this is a hello world test bla");
GetCount(list);
// release out memery here
}
I wrote that just now so it proboly wont work - but that is the general idea.
Another rough draft this time in C++ (note: std::map has pretty good search times):
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef map<string, int> CountMap;
void PushWords(CountMap& list, const char* words)
{
char ch = '\0';
unsigned int len = strlen(words);
string str;
int index = 0;
for (unsigned int i = 0; i < len; i++)
{
ch = words[i];
if (index > 0 && ch == ' ')
{
list[str] = list[str] + 1;
index = 0;
}
else if (ch != ' ')
{
str += ch;
index++;
}
}
if (index > 0 && ch == ' ')
{
list[str] = list[str] + 1;
}
}
void PrintCount(CountMap& list)
{
CountMap::iterator iter = list.begin(), end = list.end();
for (; iter != end; ++iter)
{
cout << (*iter).first << " : " << (*iter).second;
}
}
int main()
{
CountMap map;
PushWords(map, "Hello world this is a hello world test bla");
PrintCount(map);
}