我的程序如下所示,无法正确计算字符数。我还希望匹配的字符只显示一次
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct charact
{
char ch;
int occurs;
struct charact *next;
};
typedef struct charact Char;
typedef Char * ListofChar;
typedef Char * CharNode_ptr;
void letters(char name[50], ListofChar * chars_ptr);
void report(ListofChar chars);
Char * createnode(char ch);
int main(void)
{
size_t i;
char name[50]= {0};
ListofChar chars = NULL;
scanf("%49s", name);
for(i=0; i<strlen(name); i++)
{
letters(name, &chars);
report(chars);
}
return 0;
}
Char * createnode(char ch)
{
CharNode_ptr newnode_ptr ;
newnode_ptr = malloc(sizeof (Char));
newnode_ptr -> ch = ch;
newnode_ptr -> occurs;
newnode_ptr -> next = NULL;
return newnode_ptr;
}
以上是搜索列表的功能。我认为问题出在这个函数上。
void letters(char name[50], ListofChar * lst_ptr)
{
size_t i,k;
static int j=0;
ListofChar temp_ptr= *lst_ptr;
temp_ptr=malloc(sizeof(temp_ptr));
*lst_ptr=createnode(name[j]);
for(i=1; i<strlen(name); i++)
{
temp_ptr->next= createnode(name[i]);
temp_ptr=temp_ptr->next;
}
for(k=1; k<=i; k++)
{
if(createnode(name[i])==createnode(name[k]))
{
temp_ptr->occurs++;
}
}
j++;
return ;
}
这是打印输出的功能
void report(ListofChar chars)
{
ListofChar temp = chars;
temp = malloc(sizeof(chars));
if(temp == NULL)
{
printf("Empty listn");
return ;
}
for(temp = chars; temp!= NULL; temp = temp->next)
{
printf("%c: %dn", temp->ch, temp->occurs);
}
return ;
}
我当前的输出是:
你好
h: 0
e: 0
l: 0
l: 0
o: 0
这是想要的输出:
示例1:
你好
h: 1
e: 1
l: 2
o: 1
示例2:
阵列
a: 2
r: 2
y: 1
主要问题确实存在于函数letters
中,它盲目地为每个字符分配一个新节点,而不检查它是否已经在列表中。这是一个更正的版本:
void letters(char name[50], ListofChar *lst_ptr)
{
for (ListofChar *chars_ptr = lst_ptr, temp_ptr; *name; ++name)
{ // search list for character; if found, occurs one more
for (lst_ptr = chars_ptr; temp_ptr = *lst_ptr; lst_ptr = &temp_ptr->next)
if (temp_ptr->ch == *name) { ++temp_ptr->occurs; break; }
if (!temp_ptr) *lst_ptr = createnode(*name); // not found
}
}
除此之外,createnode
必须将occurs
初始化为1,并且main
应该放弃循环。