Friday, 14 October 2022

Singly linked list

 

Singly Link list :

Insert at begining, at end and at given location code in C++


#include<iostream>
using namespace std;


class node
{
private:
int data;
node *next;
node *head;
node *ptr;
node *tail;
public:
node();
void insert_at_beg();
void insert_at_end();
void inset_at_loc(int loc);
void input_func();
    void display();
 
};

node::node()
{
next=head=ptr=NULL;
}
void node::input_func()
{
ptr=new node;
cout<<"Enter your data :";
cin>>ptr->data;
}
void node::insert_at_beg()
{
input_func();
if(head==NULL)
{
head=ptr;
ptr->next=NULL;
}
else
{
ptr->next=head;
head=ptr;
}
}
void node::insert_at_end()
{
input_func();
if(head==NULL)
{
head=ptr;
ptr->next=NULL;
}
else
{
node *temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
}
void node::inset_at_loc(int loc)
{
input_func();
if(loc<=0)
{
cout<<"You entered invailed location"<<endl;
}
if(loc==1)
{
if(head==NULL)
{
head=ptr;
ptr->next=NULL;
}
else
{
ptr->next=head;
head=ptr;
}
}
else
{
node *temp=head;
for(int i=1;i<loc-1;i++)
{
temp=temp->next;
}
if(temp->next!=NULL)
{
ptr->next=temp->next;
temp->next=ptr;
}
else
{
temp->next=ptr;
ptr->next=NULL;
}
}
}
void node::display()
{
node *temp=head;
while(temp!= NULL)
{
cout<<"Data is :"<<temp->data<<""<<endl;
temp=temp->next;
}
}



int main()
{
node n;
n.insert_at_beg();
n.insert_at_beg();
n.insert_at_end();
n.inset_at_loc(2);
n.display();
return 0;
}

No comments:

Post a Comment

Fiver Account

 Fiver Account: https://www.fiverr.com/s/bPlNbN