CCCPaste

b2554b1ced9da

//Q2.2) WAP to implement a linked list, insert data at the front and then print the linked list.

#include 
#include
using namespace std;

struct node{
    int data;
    node* next;
    void setData(int d){
        data=d;
        next=NULL;
    }
};

void InsertAtHead(node* &head,int data){
    node* newNode=(node*)malloc(sizeof(node));
    newNode->setData(data);
    newNode->next=head;
    head=newNode;
}

void PrintLinkedList(node* &head){
    node* temp=head;
    while(temp!=NULL){
        cout<data<<" ";
        temp=temp->next;
    }
    cout<setData(1);

    InsertAtHead(head,2);
    InsertAtHead(head,3);
    InsertAtHead(head,4);
    InsertAtHead(head,5);

    cout<<"After Insertion: ";
    PrintLinkedList(head);

    return 0;
}
/*
    OUTPUT:

    After Insertion: 5 4 3 2 1 

*/