Sunday, March 17, 2013

Pair Wise Swapping in a Linked List


#include<stdio.h>
#include<stdlib.h>

typedef struct list
{
int info;
struct list *next;
}node;

node * head;

void insert(int data);
void display();
void pairwise_swapping(node *ptr);
void swap(int *a, int *b);

void insert(int data)
{
node *ptr , *tmp;
ptr=(node*)malloc(sizeof(node));

if(ptr==NULL)
return;

(*ptr).info=data;
(*ptr).next=NULL;
if(head==NULL)
{
head=ptr;
}
else
{
tmp=head;
while((*tmp).next!=NULL)
tmp=(*tmp).next;

(*tmp).next=ptr;
}
}

void display()
{
node * ptr;

if(head==NULL)
{
printf("list is empty\n");
return;
}

for(ptr=head;ptr!=NULL;ptr=(*ptr).next)
printf("%d ",(*ptr).info);
}

void swap(int *x , int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}

void pairwise_swapping(node *ptr)
{
node *tmp , *tmp_next;
tmp= ptr;
while (tmp!=NULL && (*tmp).next!=NULL)
{
tmp_next = (*tmp).next;
swap(&(*tmp).info , &(*tmp_next).info);
tmp=(*tmp_next).next;
}
}

main()
{
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
insert(6);
pairwise_swapping(head);
display();
}

Output:
2 1 4 3 6 5 

1 comment:

  1. C language tutorials here
    http://www.kidsfront.com/competitive-exams/computer-practice-test.html
    Free and must try website

    ReplyDelete