Reputation:
struct ll {
int num;
struct ll *next;
};
struct ll *head;
main() {
/* code to assign head pointer some memory */
print(head->next);
}
I read that the print()
function in above code moves the poiner to next item. How does this move the head pointer to next item?
Upvotes: 0
Views: 171
Reputation: 18652
Your head
pointer is a global and you don't want to alter it while simply traversing the list. This will walk through the list and print each num
field.
void print(struct ll *node) {
while (node) {
printf("%d\n", node->num);
node = node->next;
}
}
main() {
/* code to assign head pointer some memory */
print(head);
}
Upvotes: 1
Reputation: 34031
print()
must look something like:
print(struct ll *foo) {
// code
head = head->next;
// other code
}
Note that this is not good code in a variety of ways, but that's how it would move head
to point to the next item.
Upvotes: 2