链接列表和指针正确指向?

时间:2014-03-26 21:11:49

标签: c pointers linked-list

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;及其背后的逻辑会帮助我很多。

1 个答案:

答案 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;
}