DEV Community

ACHYUTKRCHAUDHARY
ACHYUTKRCHAUDHARY

Posted on

Inserting Elements at the Beginning of a Linked List

include

include

using namespace std;

class Node{
public:
int data;
Node *prev;
Node *next;

Node(int data){
    this->data=data;
    this->prev=nullptr;
    this->next=nullptr;
}
Node(int data,Node *prev , Node *next){
    this->data=data;
    this->prev=nullptr;
    this->next=nullptr;
}
Enter fullscreen mode Exit fullscreen mode

};

int main()
{
int n;
cout<<"Enter the size of array";
cin>>n;

vector<int> arr(n,0);
for(int i=0;i<n;i++){
    cin>>arr[i];
}
cout<<"The Element in the array";
for(int i=0;i<n;i++){
    cout<<arr[i]<<" ";
}
cout<<"\n";

Node *head = nullptr;
for(int i=0;i<arr.size();i++){
    if(head == nullptr){
        Node *temp = new Node(arr[i]);
        head=temp;
    }else{
        Node *temp = new Node(arr[i]);
        temp->next=head;
        head = temp;
    }
}
cout<<"The Elements in the linked list\n";
Node *curr = head;
while(curr){
    cout<<curr->data<<" ";
    curr=curr->next;
}
return 0;
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)