DATA STRUCTURES

  • Home
  • DATA STRUCTURES USING C++


Admission Enquiry Form

Insertion an element at Rear:

Insertion an element at the rear means old Node link part will have the address of new Node.




Program of insertion in the linked list at rear.

//Insertion in the linked list at rear.
#include<iostream>
#include<conio.h>
using namespace std;
struct node
{
int data;
struct node *link;
}*ptr,*start=NULL,*save;

void create_new_node(int);
void insert_new_node();
void display();

int main()
{
int item;
char ch='y';

while(ch=='y'||ch=='Y')
{
cout<<"Enter item..\n";
cin>>item;
create_new_node(item);
insert_new_node();
display();
cout<<"\nDo you want to enter more nodes press y for yes and n for no...\n";
ch=getch();
}
return 0;
}//end of main function

void create_new_node(int item)
{
ptr=new node;
ptr->data=item;
ptr->link=NULL;
}//end of create_new_node function

void insert_new_node()
{
if(start==NULL)
{
start=ptr;
save=ptr;
}
else
{
start->link=ptr;
start=ptr;
}
}//end of insert_new_node function

void display()
{
struct node *newptr;
newptr=save;
while(newptr!=NULL)
{
cout<<newptr->data<<" ->";
newptr=newptr->link;
}
}//end of display function




Insertion of the element at the beginning.

Insertion of element at the beginning means New Node link part will have the address of Old Node.

Program of insertion in the linked list at the beginning.

//Insertion in the linked list at beginning.
#include<iostream>
#include<conio.h>
using namespace std;

struct node
{
int data;
struct node *link;
}*ptr,*start=NULL,*store;

void create_new_node(int);
void insert_new_node();
void display();

int main()
{
int item;
char ch='y';

while(ch=='y'||ch=='Y')
{
cout<<"Enter item..\n";
cin>>item;
create_new_node(item);
insert_new_node();
display();
cout<<"\nDo you want to enter more nodes press y for yes and n for no...\n";
ch=getch();
}
return 0;
}//end of main function

void create_new_node(int item)
{
ptr=new node;
ptr->data=item;
ptr->link=NULL;
}

void insert_new_node()
{
if(start==NULL)
{
start=ptr;
store=ptr;
}
else
{
ptr->link=start;
start=ptr;
}
}// end of insert_new_node function

void display()
{
struct node *newptr;
newptr=start;
while(newptr!=NULL)
{
cout<<"<-";
cout<<newptr->data<<" ";
newptr=newptr->link;
}
}//end of display function