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的地址 - &gt; next,temp = &temp->next;
或者它应该是temp = *temp->next;
及其背后的逻辑会帮助我很多。
答案 0 :(得分:1)
应为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;
}