gpt4 book ai didi

c - 链表连续节点

转载 作者:行者123 更新时间:2023-11-30 19:19:43 25 4
gpt4 key购买 nike

有没有办法获取链表的5个连续元素?我想计算 3 个连续元素的总和并将其与接下来 2 个元素的总和进行比较。

我尝试将元素保存在数组中,然后检查总和,但我认为我已经摆脱了问题

for(i=0; i<size;i++)
{
array[i]=curr_item->type;
curr_item=curr_item->next;
}

for(i=0; i<size; i++)
{
sum=(array[i]+array[i+1]+array[i+2]) - (array[i+3]+array[i+4]);
if (sum>0)
printf("Successfull\n")
else
printf("Wrong\n");
}

最佳答案

要遍历一个典型的链接列表,它是这样的(C 风格):

typedef struct list{
struct list next,
int value
} list;

list * iterator = headOfList;

while(itertaor != NULL)
iterator = iterator->next;

从这里您需要做的就是在 while 循环内添加一些 if-then 逻辑,以将正确的有序元素添加在一起。例如,添加前两个元素(假设列表有两个以上元素)

int count = 0;
int sum = 0;

while(itertaor != NULL){
if(count == 0 || count == 1)
sum += iterator->value;
iterator = iterator->next;
count++;
}

如果您使用的是更用户友好的东西,您很可能能够摆脱这样的事情(伪代码):

  foreach( item in list )
if ( item is 1st, 2nd, or 3rd)
add to running sum

关于c - 链表连续节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23852844/

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