#include <iostream>
usingnamespace std;
struct abc
{
int data;
abc *next;
};
abc *head = NULL;
void insertbeg(int d)
{
abc *ptr = new abc;
ptr->data = d;
if (head == NULL) // no nood initially ! // pehli dafa to yai loop chalay gi lazmi! cuz HEAD MEIN PEHLI DAFA TO THA HI NULL!
{
head = ptr; // naye node ka address head mein save!
}
else
{
ptr->next = head; // ptr pointing to the initial node
head = ptr;// head pointing to ptr
}
}
void showdata()
{
abc *temp = head;
while (temp != NULL)
{
cout << temp->data;
temp = temp->next;
}
}
void makingnodes()
{
abc *node = new abc; //aik dynamic structure banaya hai
cout << "Enter data" << endl;
cin >> node->data;
node->next = NULL;
if (head == NULL) // no nood initially ! // pehli dafa to yai loop chalay gi lazmi! cuz HEAD MEIN PEHLI DAFA TO THA HI NULL!
{
head = node; // naye node ka address head mein save!
}
else
{
abc*temp = head; // temp pointer ko head ka address day dia shuro mein dono
while (temp->next != NULL) // temp ko chalao last tak..agay aur koi node nahi
{
temp = temp->next;
}
temp->next = node; // ab temp next yani...last node k address walay slot par node ka address copy..LINKED!
// nabeel did temp->next = &node; cuz object ka address pointer ko!
}
}
int main()
{
int y;
cout << "How many nodes you want to enter" << endl;
cin >> y;
for (int i = 0; i < y;i++)
{
makingnodes();
}
int x;
cout <<"Enter the data of the new node:" <<endl;
cin >> x;
insertbeg(x);
cout <<"Final nodes data are : " <<endl;
showdata() ;
cout <<endl;
system("pause");
}
Your code works fine, but it forces you to use a global variable and to remember to set every new ‘node’ instances to default values.
I'd add at least a basic constructor and I'd try to avoid the global variables passing my singly linked list to the functions by reference.
I’d also tried to be more consistent; I mean, if the function ‘makingnodes()' is in charge of asking the values to the user, why the ‘insertbeg()' one is not?
Is this the right way to add a node in the beginning?
No. When head==NULL, you leave node->next uninitialized.
When inserting at the beginning, the value of head doesn't matter:
1 2 3 4 5 6 7 8 9 10
// Add nodes at front
abc* insertbeg(abc*& head)
{
std::cout << "Enter the data of the new node: ";
abc *ptr = new abc;
std::cin >> ptr->data;
ptr->next = head;
head = ptr;
return ptr;
}
By the way, you should never insert at the end of a linked list unless you keep track of a tail pointer. It's just too inefficient.