c++ - 为什么我会为链表获得额外的输出
问题描述
问题是
有一组输入字符串和一组查询字符串。对于每个查询字符串,确定它在输入字符串列表中出现的次数。
字符串 = [ab,ab,abc] 查询 = [ab,abc,bc] ab 有 2 个实例,'abc' 有 1 个实例,'bc' 有 0 个实例。对于每个查询,添加一个元素。
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
struct node {
int data;
node *next;
}*first=NULL,*last= new node;
void create(int count) {
node *temp;
temp = new node;
temp->data = count;
temp->next = NULL;
if(!first) first=last=temp;
else {
last->next = temp;
last = temp;
}
}
void display() {
node *temp = first;
while(temp) {
cout<<temp->data<<endl;
temp = temp->next;
}
}
void matchStrings(string s[],string q[],int s_count,int q_count){
int counter;
// res = new int[q_count];
for(int i=0;i<=q_count;i++){
counter = 0;
for(int j=0;j<s_count;j++){
if( q[i] == s[j] ) counter++;
}
if(counter != 0) create(counter);
else create(0);
}
// return res;
}
int main() {
int string_count,query_count,*res;
cin>>string_count;
string strings[string_count];
for(int i=0;i<string_count;i++) cin>>strings[i];
cin>>query_count;
string queries[query_count];
for(int i=0;i<query_count;i++) cin>>queries[i];
matchStrings(strings,queries,string_count,query_count);
// res = matchStrings(strings,queries,string_count,query_count);
matchStrings(strings,queries,string_count,query_count);
// for(int i=0;i<query_count;i++) cout<<res[i]<<endl;
display();
return 0;
}
现在我正在尝试使用链接列表来实现它,而不是将输出作为 2、1、0。我得到的输出为 2,1,0,2,2,1,0,2。我不知道如何为超过 3 个链接创建 LL。请帮忙。
解决方案
在函数void matchStrings()
中,您编写了
for(int i=0;
i<=q_count;
i++){
而是应该
for(int i=0;
i<q_count;
i++){
由于额外的迭代,随机生成的字符串与 的集合进行检查,strings[]
结果它们被错误地匹配。
所以这会导致执行create(0)
一个额外的时间,这会导致创建一个带有数据 0 的额外节点,该节点会被打印出来。
推荐阅读
- angular - RXJS 用暂停/间隔监听
- c++ - 使用 QTreeView(或 QAbstractItemView)在项目激活时打开对话框,或单击编辑项目
- algorithm - 带约束的二分匹配
- azure - 无法访问租户间的 OneDrive 存储
- reactjs - 当 ref.current 被赋值时运行 useEffect
- javascript - 有条件地渲染组件而不会丢失“空白”空间 - ReactJS
- android - RNfirebase核心模块未找到android
- authentication - 为什么 Keycloak 使用 Session-Cookie 而不是 JWT Authorization Header
- salesforce - 使用 apex:detail 时如何获取要显示的查找类型相关列表?
- bash - 从文本文件中提取特定数据 - bash