gpt4 book ai didi

c - 链表和指针指向正确吗?

转载 作者:行者123 更新时间:2023-11-30 15:36:07 27 4
gpt4 key购买 nike

struct my_struct
{
struct my_struct *next;
int data;
};

struct my_struct *root;

那么如果我想做一些事情,比如在链表中查找具有最高数据值的结构,我应该像这样使用我的指针吗?

struct my_struct *temp = head;
struct my_struct *highest = head;

for(I = 0; I<10; I++)
{
temp = temp->next;
}

所以我的主要问题是:应该是 temp = temp->next; 还是 temp = temp->next 的地址, temp = &temp->next; 或者应该是 temp = *temp->next; ,它背后的逻辑会对我有很大帮助。

最佳答案

应该是temp = temp->next;

在c中,语法temp->next相当于(*temp).next。换句话说,它取消引用指针 temp 并提取 next 属性。您已将 next 属性定义为 my_struct*(指向 my_struct 的指针)。这与 temp 的数据类型相同,因此赋值有效。

此外,我不建议使用具有固定迭代限制的 for 循环 - 除非您已经知道列表最多只有 10 个元素。既然如此,为什么不使用数组呢?

尝试这样的循环:

struct my_struct* temp = head;
struct my_struct* highest = null;
int highestFound = -1; // or some other value known to be below all values in the list
while (temp != null) {
if(temp->data > highestFound) {
highestFound = temp->data;
highest = temp;
}
temp = temp->next;
}

关于c - 链表和指针指向正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22673148/

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