DEV Community

Divyanshu Singh
Divyanshu Singh

Posted on

inserting elements at beginning of a linked list

#include <iostream>
using namespace std;
struct Node
{
    int data;
    Node* next;
};
Node* head;
void insertAtBeginning(int x)
{
   Node* temp = new Node();
   temp->data = x;
//   temp->next = NULL;
//   if(head != NULL)
//   {
//       temp->next = head;

//   }
//   head = temp;
    temp->next = head;
    head = temp;
}
void print()
{
    Node* temp = head;
    while(temp != NULL)
    {
        cout<< temp->data << " ";
        temp = temp->next;
    }
    cout<< endl;

}
int main()
{
    head = NULL;
    int n, x;
    cout << "How many elements do you want to insert at the beginning?\n";
    cin>>n;
    for(int i = 0; i<n; i++)
    {
    cout<< "Enter the element\n";
    cin>>x;
    cout<<"The list after adding "<<x<<" is:\n";
    insertAtBeginning(x);
    print();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)