OneCompiler

SINGLY_LINKED_LIST

153

#include <iostream>
using namespace std;

struct node
{

int data;
struct node* next;
};

node* insertBegin( node* head)
{
cout<<"Inserting node in Begining "<<endl;
node * newnode=new node;
cin>>newnode->data;
newnode->next=head;
head=newnode;
return head;

}

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

}

node * inserInEnd(node* head)
{
cout<<"Inserting node in End "<<endl;
node* tmp=head;
while(tmp->next!=NULL)
{
tmp=tmp->next;
}
node * newnode=new node;
cin>>newnode->data;
tmp->next=newnode;
newnode->next=NULL;
return head;
}

node* create(node * head)
{
node *tmp,*newnode;
cout<<"Enter number of nodes"<<endl;
int n;
cin>>n;
tmp=head=new node;
cin>>tmp->data;
tmp->next=NULL;
for(int i=0;i<n-1;i++)
{
newnode=new node;
cin>>newnode->data;
newnode->next=NULL;
tmp->next=newnode;
tmp=tmp->next;
}

 return head;

}

int main()
{
node * head;
head=create( head);

  print(head);
  head=insertBegin(head);
  print(head);
  head=inserInEnd(head);
  print(head);
 
return 0;

}