So I am learning Linked Lists in C currently and I have some doubts regarding some assignments used while creating a Linked List and Inserting nodes. I hope to understand how does the memory stuff works in the background.
struct node {
int data;
struct node *next
}
void createList(int n, struct node *head)
{
struct node *temp, *newnode;
//Assignment 1
temp = head;
//Assignment2
temp->next = newnode
//somethings
}
Some Context : head does not contain any data. It is just the first entry point node and it points to the first node that contains any data?
temp is used for traversal and newnode is the newly created node and is changed to temp later.
How do the two assignments above work in terms of memory? In Assignment 1, am I copying contents or do the two names point to same location? Same doubts for Assignment 2.
Updated , the significant code is below.
int menu()
{
int choice = 0;
printf("\n\t\tMENU\n1.Create Linked List");
printf("\n2.Display Linked List");
printf("\nAny other number to exit\n");
printf("\nEnter Choice : ");
scanf("%d", &choice);
return choice;
}
void createList(int n, struct node *head)
{
int data;
struct node *temp, *newNode;
temp = head; // 'head' node with no data pointing towards 'temp'
for (int i = 1; i <= n; i++)
{
newNode = malloc(sizeof(struct node));
printf("Enter Data %d : ", i);
scanf("%d", &data);
newNode->data = data; // First Node
newNode->next = NULL;
temp->next = newNode;
temp = temp->next;
}
}
void displayList(struct node *head)
{
struct node *temp;
temp = head->next; // Link to First Node
int i = 1;
printf("\nStart Display\n");
while (temp != NULL)
{
printf("\nData %d : %d\n", i, temp->data);
temp = temp->next;
i++;
}
}
void main()
{
int choice, n;
struct node *head;
head = malloc(sizeof(struct node));
head->next = NULL;
label:
choice = menu();
switch (choice)
{
case 1:
printf("Enter Number of Entries : ");
scanf("%d", &n);
createList(n, head);
goto label;
break;
case 2:
displayList(head);
goto label;
break;
default:
printf("Wrong Choice");
exit(0);
break;
}
}
Edit 2 : Another doubt :
temp = temp->next
This is used for traversal but how does it work. 'next' is a sublocation in the 'struct node' which has address to next node right ? So what happens with this assignment, in the memory location ?
Would appreciate the help as this topic is turning out to be very hard to understand.
temp->next = newnode;is invalid becausenewnodecontains an uninitialized value.headinitialized before you pass it tocreateList?