gpt4 book ai didi

C - 在二叉搜索树中打印字符串的有序 3-Anagrams

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:13 25 4
gpt4 key购买 nike

C 中的这段代码输入了一个整数和一个字符串,并应在输出中按字典顺序给出字符串的 3 个连续字母的所有字谜。

EXAMPLE:
Input
3
mississippi
Output
ipp
iss
iss
mis
ppi
sip
sis
ssi
ssi

它没有,而是只给出最后一个 3-gram 重复 n 次,其中 n=可能的 3-gram 的数量。

我使用字符串的二叉搜索树来记住每个字谜,我不能使用简单的字符串数组,因为练习需要这样做。为了按顺序打印字符串,它会进行对称访问(从左到右)。

我做了一些调试测试,我认为问题出在插入函数上,可能是我把标点符号弄得一团糟。

如果有人想看一下,我将不胜感激

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

typedef struct nodo
{
char * key;
int dim;
struct nodo * left;
struct nodo * right;
} Nodo;
typedef Nodo* albero;


/*int dimensions (albero t)
{
int d;
if (t==NULL) return 0;
else d=(1+dimensions(t->left)+dimensions(t->right));
t->dim=d;
return d;
}*/

simmetrica(albero t,int z)
{
if (t!=NULL)
{
simmetrica(t->left,z);
/*if ((t->dim)>=z)*/ printf("%s\n",t->key);
simmetrica(t->right,z);
}
}

Nodo* insert(albero t, char* key)
{
Nodo* new = malloc(sizeof(Nodo));
new->key=key;
new->dim=0;
new->right=NULL;
new->left=NULL;
if(t==NULL)
{
return new;
}
Nodo* parent;
Nodo* current=t;
while(current!=NULL)
{
parent=current;
if/*(current->key<key)*/(strcmp(current->key,key)<0)
{
current=current->right;
}
else
{
current=current->left;
}
}
if/*(parent->key<key)*/(strcmp(parent->key,key)<0)
{
parent->right=new;
}
else parent->left=new;
return t;
}




int main()
{
int z;
char s[501];
char trip[4];
albero t=malloc(sizeof(Nodo));
t=NULL;
scanf("%d", &z);
scanf("%s", s);
int o=0;
while (s[o+2] !='\0')
{ //printf("debug %d\n",o);
trip[0]=s[o];
trip[1]=s[o+1];
trip[2]=s[o+2];
trip[3]='\0';
//printf("trip %s\n",trip);
t=insert(t, trip);
o++;
}
//dimensions(t);
simmetrica(t,z);
return 0;
}

最佳答案

一切都与存储有关。 trip 已分配存储空间。它存在于某个地址,假设它是 0x401fc。当您执行插入操作时,您将地址 0x401fc 传递到 insert 中。 Insert 创建一个类型为 struct nodo 的新记录,并将地址 0x401fc 复制到字段 key 中。

然后您继续更改 trip 中的值,这会更改 0x401fc 中的值,现在所有 struct nodo 都指向新值(value)观。

要么做一个 new-> key= strdup(key) 要么让 struct nodo 有一个 char key[4] ; 然后做一个 strcpy()。任一解决方案都会创建新的存储空间。第一个在短期内是一个更简单的修复,但处理起来会更麻烦(因为它与结构分开存储)。第二种形式需要更多初始更改,但会更容易取消分配内存。

关于C - 在二叉搜索树中打印字符串的有序 3-Anagrams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21314361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com