Skip to content

Instantly share code, notes, and snippets.

@gallirohik
Last active April 16, 2018 19:09
Show Gist options
  • Select an option

  • Save gallirohik/c2d992a5f6e5d2c88c2cce0595e16ea9 to your computer and use it in GitHub Desktop.

Select an option

Save gallirohik/c2d992a5f6e5d2c88c2cce0595e16ea9 to your computer and use it in GitHub Desktop.
swap pair in a linked list
#include <stdio.h>
#include <stdlib.h>
struct tnode
{
int data;
struct tnode *link;
};
typedef struct tnode *tptr;
tptr insert(tptr first,int x)
{
tptr p,t;
p=(tptr)malloc(sizeof(struct tnode));
p->data=x;
p->link=NULL;
if(first==NULL)
{
first=p;
return first;
}
t=first;
while(t->link!=NULL)
t=t->link;
t->link=p;
return first;
}
void display(tptr first)
{
tptr t;
t=first;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->link;
}
}
void swap(tptr t1,tptr t2)
{
int temp;
temp=t1->data;
t1->data=t2->data;
t2->data=temp;
}
void pairswap(tptr first)
{
tptr next,temp,t1,t2;
temp=first;
while(temp!=NULL)
{
t1=temp;
if(temp->link==NULL)
break;
t2=temp->link;
next=t2->link;
swap(t1,t2);
temp=next;
}
}
int main()
{
int x;
tptr first;
first=NULL;
scanf("%d",&x);
while(x!=-1)
{
first=insert(first,x);
scanf("%d",&x);
}
pairswap(first);
display(first);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment