Some other operations on linked list...Enjoy.;)
1.To display the linked list from back..
void display_back(struct node *p)
{
struct node *temp,*temp1;
if(p->next==NULL)
{
printf("%d\n",p->data);
return;
}
temp=p;
while(temp->next!=NULL)
{
temp1=temp;
temp=temp->next;
}
temp1->next=NULL;
printf("%d\n",temp->data);
display_back(p);
}
2.To compare two given linked list..
int cmp(struct node *p,struct node *q)
{
while(p!=NULL || q!=NULL)
{
if(p->data!=q->data)
return 0;
else
{
p=p->next;
q=q->next;
}
}
if(p!=NULL || q!=NULL)
return 0;
else
return 1;
}
3.To swap the Kth node from the start with the Kth node from the last...
void swap(struct node *ps,int k)
{
struct node *p,*q,*r;
p=ps;
q=ps;
r=ps;
int i=1;
while(i<k && p!=NULL)
{
p=p->next;
q=q->next;
i++;
}
if(i!=k || p==NULL)
{
printf("less no of nodes\n");
return;
}
while(q->next!=NULL)
{
q=q->next;
r=r->next;
}
int temp;
temp=p->data;
p->data=r->data;
r->data=temp;
}
4.To find the mid of linked list..
int find_mid(struct node *p)
{
struct node *temp,*temp1;
temp=p;
temp1=p;
int i;
for(i=1;temp->next!=NULL;i++,temp=temp->next)
{
if(i%2==0)
temp1=temp1->next;
}
return temp1->data;
}
5.To create a copy of linked list..
void cpy(struct node *p,struct node **q)
{
struct node *temp,*temp1;
while(p!=NULL)
{
temp=(struct node *)malloc(sizeof(struct node));
temp->data=p->data;
temp->next=NULL;
if(*q==NULL)
*q=temp;
else
{
temp1=*q;
while(temp1->next!=NULL)
temp1=temp1->next;
temp1->next=temp;
}
p=p->next;
}
}
1.To display the linked list from back..
void display_back(struct node *p)
{
struct node *temp,*temp1;
if(p->next==NULL)
{
printf("%d\n",p->data);
return;
}
temp=p;
while(temp->next!=NULL)
{
temp1=temp;
temp=temp->next;
}
temp1->next=NULL;
printf("%d\n",temp->data);
display_back(p);
}
2.To compare two given linked list..
int cmp(struct node *p,struct node *q)
{
while(p!=NULL || q!=NULL)
{
if(p->data!=q->data)
return 0;
else
{
p=p->next;
q=q->next;
}
}
if(p!=NULL || q!=NULL)
return 0;
else
return 1;
}
3.To swap the Kth node from the start with the Kth node from the last...
void swap(struct node *ps,int k)
{
struct node *p,*q,*r;
p=ps;
q=ps;
r=ps;
int i=1;
while(i<k && p!=NULL)
{
p=p->next;
q=q->next;
i++;
}
if(i!=k || p==NULL)
{
printf("less no of nodes\n");
return;
}
while(q->next!=NULL)
{
q=q->next;
r=r->next;
}
int temp;
temp=p->data;
p->data=r->data;
r->data=temp;
}
4.To find the mid of linked list..
int find_mid(struct node *p)
{
struct node *temp,*temp1;
temp=p;
temp1=p;
int i;
for(i=1;temp->next!=NULL;i++,temp=temp->next)
{
if(i%2==0)
temp1=temp1->next;
}
return temp1->data;
}
5.To create a copy of linked list..
void cpy(struct node *p,struct node **q)
{
struct node *temp,*temp1;
while(p!=NULL)
{
temp=(struct node *)malloc(sizeof(struct node));
temp->data=p->data;
temp->next=NULL;
if(*q==NULL)
*q=temp;
else
{
temp1=*q;
while(temp1->next!=NULL)
temp1=temp1->next;
temp1->next=temp;
}
p=p->next;
}
}
No comments:
Post a Comment