Write a C program to swap mth and nth element of singly linked list


#include

#include

#include

struct node

{

int data;

struct node *link;

}*head,*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("\nWant to add another node(Y|N): ");

scanf("%s",&ch);

}

display();

swap();

count();

display();

getch();

}

void create()

{

temp=malloc(sizeof(struct node));

printf("\nEnter the elements for singly linked list: ");

scanf("%d",&temp->data);

temp->link=NULL;

if(head==NULL)

head=temp;

else

{

q=head;

while(q->link!=NULL)

{

q=q->link;

}

q->link=temp;

}

}

void display()

{

if(head==NULL)

printf("\nlinked list is empty");

else

{

printf("\nElement in singly linked list are: \n");

q=head;

while(q!=NULL)

{

printf("%d\n",q->data);

q=q->link;

}

}

}

void swap()

{

int i;

printf("\nEnter Mth and Nth position of singly linked list for swaping: ");

scanf("\n%d%d",&m,&n);

count();

if(m>0&&m<=cnt&&n>0&&n<=cnt)

{

q=head;

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->link;

}

}

else

printf("\nyou entered wrong position please try again");

}

int count()

{

cnt=0;

q=head;

while(q!=NULL)

{

cnt++;

if(cnt==m)

num1=q->data;

if(cnt==n)

num2=q->data;

q=q->link;

}

return cnt;

}

/* OUTPUT


Enter the elements for singly linked list: 10


Want to add another node(Y|N): y


Enter the elements for singly linked list: 20


Want to add another node(Y|N): y


Enter the elements for singly linked list: 30


Want to add another node(Y|N): y


Enter the elements for singly linked list: 40


Want to add another node(Y|N): n


Element in singly linked list are:

10

20

30

40


Enter Mth and Nth position of singly linked list for swaping:

2

3


Element after swapping

Element in singly linked list are:

10

30

20

40 */
Write a C program to swap mth and nth element of singly linked list Write a C program to swap mth and nth element of singly linked list Reviewed by on November 17, 2013 Rating: 5
Powered by Blogger.