/*write a c program to swap mth and nth element of singly linked list
*/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *next;
}*start,*q,*temp,*t;
int cnt,num1,num2,m,n;
void create();
void display();
void swap();
int count();
void main()
{
int ch='y';
clrscr();
while(ch=='y'||ch=='Y')
{
create();
printf("\ndo you want to enter(Y|N):-");
scanf("%s",&ch);
}
display();
swap();
count();
display();
getch();
}
void create()
{
temp=malloc(sizeof(struct node));
printf("\nenter the number:-");
scanf("%d",&temp->data);
temp->next=NULL;
if(start==NULL)
start=temp;
else
{
q=start;
while(q->next!=NULL)
{
q=q->next;
}
q->next=temp;
}
}
void display()
{
if(start==NULL)
printf("\nlinked list is empty");
else
{
printf("\nelement in singly linked list are:-\n");
q=start;
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->next;
}
}
}
void swap()
{
int i;
printf("\nenter two position of a element which you want to swap");
scanf("%d%d",&m,&n);
count();
if(m>0&&m<=cnt&&n>0&&n<=cnt)
{
q=start;
i=0;
printf("\n\nelement after swapping");
while(q!=NULL)
{
i++;
if(m==i)
q->data=num2;
if(n==i)
q->data=num1;
q=q->next;
}
}
else
printf("\nyou entered wrong position please tyr again");
}
int count()
{
cnt=0;
q=start;
while(q!=NULL)
{
cnt++;
if(cnt==m)
num1=q->data;
if(cnt==n)
num2=q->data;
q=q->next;
}
return cnt;
}
/*
enter the number:-1
do you want to enter(Y|N):-y
enter the number:-4
do you want to enter(Y|N):-y
enter the number:-8
do you want to enter(Y|N):-y
enter the number:-2
do you want to enter(Y|N):-y
enter the number:-8
do you want to enter(Y|N):-n
element in singly linked list are:-
1
4
8
2
8
enter two position of a element which you want to swap1 5
element after swapping
element in singly linked list are:-
8
4
8
2
1
*/
No comments:
Post a Comment