using namespace std;
struct node
{
int info;
struct node *next;
struct node *getnode();
struct node *insert_last(struct node *);
struct node *insert_begin(struct node *);
struct node *insert_after(struct node *);
struct node *delete_after(struct node *);
void display(struct node *);
};
struct node* node:: getnode()
{
int x;
struct node *p;
p=new node;
cout<<"enter the information ";
cin>>x;
p->info=x;
p->next=NULL;
return(p);
}
struct node* node::insert_last(struct node *ptr)
{
struct node *temp;
temp=ptr;
while(temp->next!=NULL)
temp=temp->next;
temp->next=getnode();
return(ptr);
}
struct node* node::insert_begin(struct node *ptr)
{
struct node *temp;
temp=ptr;
temp=getnode();
temp->next=ptr;
ptr=temp;
return(ptr);
}
struct node* node::insert_after(struct node *ptr)
{
struct node *temp1,*temp2;
int x,i;
temp2=temp1=ptr;
cout<<"enter the position";
cin>>x;
for(i=1;i<(x-1);i++)
{
temp1=temp1->next;
temp2=temp2->next;
}
temp2=temp2->next;
temp1->next=getnode();
temp1=temp1->next;
temp1->next=temp2;
return(ptr);
}
struct node* node::delete_after(struct node *ptr)
{
int x,i;
struct node *temp1,*temp2;
temp1=temp2=ptr;
cout<<"enter your position";
cin>>x;
for(i=1;i<(x-1);i++)
{
temp1=temp1->next;
temp2=temp2->next;
}
temp2=temp2->next;
temp1->next=temp2->next;
return(ptr);
}
void node:: display(struct node *ptr)
{
struct node *temp;
temp=ptr;
while(ptr!=NULL)
{
cout<
ptr=ptr->next;
}
}
int main()
{
struct node *head,a;
int ch;
head=a.getnode();
while(1)
{
cout<< "options:-\npress 1 for insert at last\npress 2 for insert at begin\n press 3 for insert in between\n press 4 for delete\n press 5 for display\n press any key for exit"<<"\n\n";
scanf("%d",&ch);
switch(ch)
{
case 1://head=n.getnode();
head=a.insert_last(head);
break;
case 2:
head=a.insert_begin(head);
break;
case 3:
head=a.insert_after(head);
break;
case 4:
head=a.delete_after(head);
break;
case 5:
a.display(head);
break;
default:
exit(1);
}
}
}
can anyone tell me efficient logic to implement a linklist having cycle
ReplyDelete