I was trying to implement basic operations of a Linked list using structures and classes but I usually mess up something. I am confused about memory allocation here. For example, why this program is not working correctly?
#include<iostream>
using namespace std;
struct node{
int data;
node* link;
};
node* head;
void insert(int x){
node temp;
temp.data = x;
temp.link = head;
head = &temp;
}
void print_list(){
node* temp = head;
cout<<"The list is:\n";
while(temp!=NULL){
cout<<temp->data<<" ";
temp = temp->link;
}
}
int main(){
head = NULL;
cout<<"How many numbers?\n";
int n;
cin>>n;
while(n--){
cout<<"\nEnter value:\n";
int value;
cin>>value;
insert(value); // This function inserts node at beginning of the list
print_list();
}
return 0;
}
But if I change the insert function to this, it works
void insert(int x){
node* temp = new node();
temp->data = x;
temp->link = head;
head = temp;
}
Also, could somebody please suggest me a good website to learn linked list, trees and graphs?