A simple singly linked list needs nodes with each node having a data and next field. Further more, it needs a "head" pointer to point to the first node. Now if we want to run along this list say to get data from each node or even to count the nodes, we could make a node pointer, lets call it "current".
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
void Push(struct node** headRef, int data) {
struct node* newNode = malloc(sizeof (struct node));
newNode->data = data;
newNode->next = *headRef;
*headRef = newNode;
}
int main ()
{
int n;
struct node* head= NULL;
Push(&head, 3);
Push(&head, 2);
Push(&head, 1);
struct node* current= head;
current= current->next;
printf("%d", current->data);
return 0;
}
I assure you all, it compiles and runs well as it should.
The code basically builds a list by adding to the head of the list the numbers 1, 2 and 3 through the function "Push". Note that head points to the beginning of the list. Now I made a "current" pointer that was initialized to point to whatever head was pointing to. And head, was initially pointing to NULL but after the list got built, it pointed to the beginning node of a 3 node list.
Now the point of my question.
When I was initially building this code, my line 23:
Code:
struct node* current= head;
was in line 20 and as a result the programme kept crashing when run.
So my question is: How does by changing the line at which current pointer points to head, effect this?
It doesnt make sense to me. No matter where I write the code that stipulates current points to head shouldnt matter. Because head is constantly pointing to the beginning of the list.