Here are both of My Codes. One Using structure and Another Using Pointer to Structure. But when I am not using a Pointer it's not working. Al though I think they are same. But I am still a beginner. So I need to understand what's going wrong.
Not Working Code:
struct Node{
int data;
struct Node* next;
};
void insert(struct Node** head_ref,int data){
//Not Working Here. The Header should change after every insert but it isn't Moving from it's Memory;
struct Node temp ;
temp.data = data;
temp.next = (*head_ref);
(*head_ref) = &temp;
}
int main(){
struct Node *head = NULL;
insert(&head,4);
insert(&head,2);
insert(&head,11);
insert(&head,9);
while(head->next !=0 ){
std::cout << head->data <<" ";
head = head->next;
}
return 0;
}
Working Code:
struct Node{
int data;
struct Node* next;
};
void insert(struct Node** head_ref,int data){
//The Problem is in This Line. Pointer to Structure is Working But only Structure isn't
struct Node* temp = (struct Node*) malloc(sizeof(struct Node)) ;
temp->data = data;
temp->next = (*head_ref);
(*head_ref) = temp;
}
int main(){
struct Node *head = NULL;
insert(&head,4);
insert(&head,2);
insert(&head,11);
insert(&head,9);
while(head->next !=0 ){
std::cout << head->data <<" ";
head = head->next;
}
return 0;
}