gpt4 book ai didi

c - 通用C程序

转载 作者:行者123 更新时间:2023-11-30 18:31:58 24 4
gpt4 key购买 nike

以下代码;

typedef struct chainCell{
int data;
struct chainCell* next;
} chainCell;

bool sameValues (chainCell *x, chainCell *y)
{
if ((x == NULL) & (y == NULL)) return true;
if ((x == NULL) | (y == NULL)) return false;
bool same = true;
chainCell *xp = x, *yp = y; // scan pointers
while ((xp != NULL) & (same == true)) // point A
{
if (xp->data != yp->data) same = false;
xp = xp->next;
yp = yp->next;
if (((xp == NULL) & (yp != NULL)) // point B
| ((xp != NULL) & (yp == NULL)))
same = false;
};
return same;
};

我很困惑为什么循环控制包含(same == true)

B点的if语句的作用是什么?我不确定 boolean 表达式正在检查什么?

任何有助于进一步理解的帮助将不胜感激!

最佳答案

它检查两个链接列表是否包含相同的值。

显然,如果一个列表较短,它们就不相同(B 点)。

注意:我认为这里使用 break/return 会是更好的选择,它使代码更具可读性。

注2:如注释中所述,这些应该是逻辑运算符。它按原样工作,但有点令人困惑。

注3:您可以将测试移至循环内的循环之前 (while(1)),这样就无需在循环末尾进行测试。

这只是一个丑陋的代码,应该是大约 5 行代码,而不是十几行......

bool sameValues (chainCell *x, chainCell *y)
{
while(1) {
if (!x && !y) return true;
if (!x || !y) return false;
if (x->data != y->data) return false;
x = x->next;
y = y->next;
}
return false; //this is just to suppress compiler warning.
};

关于c - 通用C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18231393/

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