微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我会得到链表的额外输出

如何解决为什么我会得到链表的额外输出

问题是

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

字符串 = [ab,ab,abc] 查询 = [ab,abc,bc] 有实例 2 ab,1 个 'abc' 和 0 个 'bc'。为每个查询添加一个元素。

#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,query_count);
    matchStrings(strings,query_count);
    

    // for(int i=0;i<query_count;i++) cout<<res[i]<<endl;

    display();


    return 0;
}

现在我正在尝试使用链表来实现它,而不是将输出作为 2,1,0。 我得到的输出为 2,2,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 的节点,并被打印出来。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。