#include<bits/stdc++.h>
#include<vector>
using namespace std;
class Node {
public :
int data;
Node *next;
Node()
{
data = 0;
next = NULL;
}
Node (int a)
{ data = a;
next = NULL;
}
};
void push(Node **head_ref , int n)
{
Node *new_node = new Node();
new_node -> data = n;
new_node -> next = *head_ref;
*head_ref = new_node;}
void display(Node *head_ref)
{ while(head_ref != NULL)
{
cout << head_ref -> data << " ";
head_ref = head_ref-> next;
}
}
int main()
{ Node *head = new Node();
push (&head ,1 );
push(&head ,0 );
push(&head , 1);
display(head);
return(9);}
This when executed returns 1 0 1 0 as output , First i thought it is because of constructors but later I came to know that it is not something causing the problem.
Node *head = new Node();
Creates the extra node. Instead use
Node *head = nullptr;
or, if using an older compiler,
Node *head = NULL;
to point head
at a safe location until legitimate nodes are added.