如何从给定的单链表中添加交替节点的数据?
例如,假设我们有6个节点,数据为以下整数:1 2 3 4 5 6。因此,我们应该将所有备用节点相加为1+3+5=9,类似地2+4+6=12,因此输出应该是13和11。
我的方法很糟糕,因为它崩溃了,这里是:
while(temp->next!=NULL)
{
if(temp->next->next!=NULL)
{
sum=temp->data + temp->next->next->data;
}
else
{
sum=sum+temp->data;
}
return sum;
} //similarly i did for adding other alternate node data
谁能建议我最好的方法?
似乎您应该通过为两者准备total变量来交替进行聚合。
下面的例子
int ff = 0, sum[2] = {0};
while(temp){
sum[ff] += temp->data;
temp = temp->next;
ff = !ff;//0 -> 1, 1-> 0
}
printf("%d, %dn", sum[0], sum[1]);
//Using a pointer if there is a need to return a value to the caller as a function
//*out1 = sum[0];*out2 = sum[1];
void sum(node_type *temp, int *out1, int *out2){
int ff = 1, sum[2] = {0};
for(;temp; temp = temp->next)
sum[ff = !ff] += temp->data;
out1 && (*out1 = sum[0]);//call E.g sum(head, &sum1, &sum2);//sum(head, &sum1, NULL);sum(head, NULL, &sum2);
out2 && (*out2 = sum[1]);
}
由于您想要返回两个int
,因此为输出创建一个struct
:
struct sum_output
{
int first;
int second;
};
将其作为函数的返回类型。
struct sum_output sum(node* list);
通过迭代列表的节点,计算struct
的first
和second
成员并返回。
struct sum_output sum(node* list)
{
struct sum_output ret = {0, 0};
for ( ; list != NULL; list = list->next )
{
ret.first += list->data;
if ( list->next != NULL )
{
ret.second += list->next->data;
list = list->next;
}
}
return ret;
}