第一是逐行读取文件,根据空格拆分单词
第二是链表检索单词,找到则该节点的计数器加一,找不到则加新节点
第三是节点有序插入,比较节点单词大小插入合适位置
第四是节点数据结构,串记录单词,整型为计数器,创建新节点时计数器为1
#include <string>
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
typedef struct _NODE
{
string word;
int count;
_NODE *next;
}NODE,*PNODE;
PNODE head = NULL;
PNODE searchString(string word)
{
PNODE p = head;
while(p != NULL)
{
if(p->word == word)
return p;
p = p->next;
}
return NULL;
}
PNODE addNode(string word)
{
PNODE p = searchString(word);
if(p != NULL)
p->count++;
else
{
p = new NODE;
p->word = word;
p->count = 1;
p->next = NULL;
//
if(head == NULL || word < head->word)
{
p->next = head;
head = p;
return head;
}
else
{
PNODE q = head;
PNODE prev = q;
while(q != NULL)
{
if(word < q->word)
{
p->next = q;
prev->next = p;
break;
}
prev = q;
q = q->next;
}
if(q == NULL)
prev->next = p;
}
}
return head;
}
void print()
{
PNODE p = head;
while(p != NULL)
{
cout<<p->word<<" "<<p->count<<endl;
p = p->next;
}
}
void main()
{
ifstream file("D:\\textfile.txt");
if(!file.is_open())
{
cout<<"can't open this file"<<endl;
return;
}
char buf[1024];
while(!file.eof())
{
file.getline(buf,1024);
char *p= strtok (buf, " ,!." );
while(p != NULL)
{
head = addNode(p);
p= strtok (NULL, " ,!." );
}
}
file.close();
//
print();
}
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632