仅在C中的链表中追加唯一值
这是我的append函数,用于将元素添加到子列表中。但我的问题是,它只应该附加后跟字符串的唯一值。这意味着:仅在C中的链表中追加唯一值,c,linked-list,append,C,Linked List,Append,这是我的append函数,用于将元素添加到子列表中。但我的问题是,它只应该附加后跟字符串的唯一值。这意味着: typedef struct child {int count; char word[100]; inner_list*next;} child; typedef struct parent { char data [100]; child * head; int count; parent * next; } parent; void append(child **q,char nu
typedef struct child {int count; char word[100]; inner_list*next;} child;
typedef struct parent
{ char data [100];
child * head;
int count;
parent * next; } parent;
void append(child **q,char num[100],int size)
{ child *temp,*r,*temp2,*temp3;
parent *out=NULL;
temp = *q;
temp2 = *q;
temp3 = *q;
char *str;
if(*q==NULL)
{ temp = (child *)malloc(sizeof(child));
strcpy(temp->word,num);
temp->count =size;
temp->next=NULL;
*q=temp;
}
else
{ temp = *q;
while(temp->next !=NULL)
{ temp=temp->next;
}
r = (child *)malloc(sizeof(child));
strcpy(r->word,num);
r->count = size;
r->next=NULL;
temp->next=r;
}
}
政府应采取行动:
Inputs : aaa bbb aaa ccc aaa bbb ccc aaa
我希望我能说清楚。有什么想法吗?请询问更多信息
我尝试的是检查以前输入的元素和新元素。我有点失败了
For aaa string there should be a list like bbb->ccc(Not bbb->ccc->bbb since bbb is already there if bbb is coming more than one time it should be increase count only.)
For bbb string there should be list like aaa->ccc only
For ccc string there should be list like aaa only
这就是我到目前为止所尝试的。通过这个搜索函数,我可以控制元素是否在这里。但它失败了。如果我理解正确,考虑到输入
int search(child *p)
{
child *temp= (child *)malloc(sizeof(child));
int var =0;
char num[100];
temp = p;
strcpy(num,p->word);
while(temp->next!=NULL)
{
if(strcmp(temp->word,num)==0)
var =1;
temp=temp->next;
}
return var;
}
您希望父列表包含3个元素—一个用于aaa
的子列表,一个用于bbb
的子列表,一个用于ccc
aaa
的列表应该包含原始输入中aaa
后面的所有字符串,这里就是bbb
和ccc
。每个节点只应包含一次,相应节点中的count
变量递增,以便bbb
的计数为2,ccc
的计数为1
这是正确的吗?如果是,请继续阅读
aaa bbb aaa ccc aaa bbb ccc aaa
我认为这会让你达到你想要的目的。你需要在while循环中添加另一个条件:
for every string S in your input
{
if S is not associated with a child list in the parent
{
create a new child list associated with S at the end of the parent list
}
// now we have C, the child list we either found above or created
if there is a string S' after S
{
find the element S' in the child list C by iterating through it
if you don't find the element S', create/append it with count = 1
else when you find the element, increment its count
}
}
基本上只是扩展它,将当前迭代中的值与输入值进行比较。如果两者相等,那么只需从
append
返回即可。这不是免费代码超市,这是一个问答网站。试着自己解决问题,当你发现一个你试图解决但失败的特定问题时回来。正如你所看到的,我问的是一个想法,而不是一个免费的代码。这是一个具体的问题。您对内部列表的定义在哪里?以及向父级添加内容的代码?事实上,您在该方法中所做的只是分配一个新节点,并有选择地将其附加到现有的内部\u列表
,而没有任何建议,即使是您所要求的行为的一部分。你能展示一下你试过什么吗?如果是这样,@LuckySlevin,你的想法是在列表中查找,如果有新值,就不要添加它。@Blair我会在短时间内添加我试过的内容。很高兴我能帮上忙!另一个指针-在您的代码中使用strncpy
而不是strcpy
,以防止溢出。我也感谢您没有通过给出想法来判断和帮助我。
while(temp->next !=NULL)