首页 > 解决方案 > 为什么我会为链表获得额外的输出

问题描述

问题是

有一组输入字符串和一组查询字符串。对于每个查询字符串,确定它在输入字符串列表中出现的次数。

字符串 = [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。请帮忙。

标签: c++data-structureslinked-list

解决方案


在函数void matchStrings()中,您编写了

for(int i=0;i<=q_count;i++){

而是应该

for(int i=0;i<q_count;i++){

由于额外的迭代,随机生成的字符串与 的集合进行检查,strings[]结果它们被错误地匹配。

所以这会导致执行create(0)一个额外的时间,这会导致创建一个带有数据 0 的额外节点,该节点会被打印出来。


推荐阅读