Hi,
I have a piece of code that is demonstrating a linked list. What I don't understand is what's happening in the add function.
There is a pointer to a pointer '**q'. Further down a pointer variable is assigned 'temp = *q'
Why do I have to use '**q' as a parameter in the add function?
My code is:
Code:
# include<stdio.h>
# include<malloc.h>
/* define the node */
struct node {
int data;
struct node *next;
};
/* Add a node to the linked list */
void add(struct node **q, int num) {
struct node *temp;
temp = *q;
/* first time there is no node therefore allocate */
if(*q==NULL) {
*q=malloc(sizeof(struct node));
temp = *q;
}
/* add node after the last one */
else {
/* move on until the last node then create a new node*/
while((temp->next)!=NULL) {
temp = temp->next;
}
temp->next = malloc(sizeof(struct node));
temp = temp->next;
}
// set data and pointer for the node, the last one always point at NULL
temp->data = num;
temp->next = NULL;
}
/* Display the linked list */
void display(struct node *pt) {
// traverse through all nodes until the last one
while(pt!=NULL) {
printf(" Data : %d\n",pt->data);
printf(" next : %p\n",pt->next);
pt = pt->next;
}
}
/* ******* MAIN ******* */
int main() {
int continue_add; // used if you want to continue adding elements
int your_choice; // user choice of what to do
int num; // user data
struct node *ptr; // always pointing at the first node after first have been added
/* init values */
ptr = NULL;
continue_add = 1;
while (continue_add == 1) {
printf(" Main Menu\n");
printf(" 1. Add element\n");
printf(" Enter your choice ");
scanf("%d",&your_choice);
switch(your_choice) {
case 1:
printf(" Enter data to your node -> ");
scanf("%d",&num);
add(&ptr,num);
display(ptr);
break;
default:
printf(" Illegal choice! ");
}// switch(your_choice)
printf(" Do you want to continue (press 1 for yes) ");
scanf("%d",&continue_add);
printf("\n");
}// while (continue_add==1)
}// main()