Mike John
Mike John

Reputation: 818

Linked List and Pointers Pointing correctly?

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

struct my_struct *root;

Then if I want to do something like find the struct in the linked list with the highest data value should I use my pointers like this?

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

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

So my main question is: should it be temp = temp->next; or should it be temp = address of temp->next, temp = &temp->next; or should it be temp = *temp->next; and the logic behind it would help me a lot.

Upvotes: 0

Views: 51

Answers (1)

Michael W
Michael W

Reputation: 91

It should be temp = temp->next;

In c, the syntax temp->next is equivalent to (*temp).next. In other words, it dereferences the pointer temp and extracts the next attribute. You have defined the next attribute as a my_struct* (pointer to a my_struct). This is the same data type as temp, so the assignment works.

Also, I wouldn't recommend using a for loop with a fixed iteration limit--not unless you already know that the list will only ever have at most 10 elements. And in that case, why not use an array?

Try a loop like this:

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

Upvotes: 1

Related Questions