讀取英文文本文件,統計單詞出現頻率(不區分大小寫,忽略標點),輸出前 10 高頻詞。
string word; int count; Node* next; — 動態增長,無容量上限。isalpha 判斷屬於單詞,非字母作為分隔符。統一轉小寫。count++;count=1。count 降序排序(插入排序或轉 vector 再 sort)。word count。struct Node {
string word; int count; Node* next;
Node(string w):word(w),count(1),next(nullptr){}
};
Node* head = nullptr;
string token;
char ch;
while(in.get(ch)){
if(isalpha(ch)) token += tolower(ch);
else if(!token.empty()){
// 查找或插入
Node *p=head, *prev=nullptr;
for(; p; prev=p, p=p->next)
if(p->word == token){ p->count++; break; }
if(!p){
Node* nn = new Node(token);
nn->next = head; head = nn;
}
token.clear();
}
}
// 文件結尾可能剩餘 token
if(!token.empty()){ /* 同上 */ }
// 排序:轉 vector 便於 std::sort
vector vec;
for(Node* p=head; p; p=p->next) vec.push_back(p);
sort(vec.begin(), vec.end(),
[](Node* a, Node* b){ return a->count > b->count; });
for(int i=0;iword<<' '<count<<'\n';
// 釋放內存
for(Node* p=head; p;){ Node* t=p->next; delete p; p=t; }
unordered_map 替代鏈表,查找 O(1),代碼更簡潔。