Q. ) DIVIDE THE GIVEN LINK LIST INTO TWO LINK LIST ONE IS FIRST LIST AND ANOTHER ONE IS SECOND LIST.
example--
list-{1,2,3,4,5,6}
list1={1,2,3}
list2={4,5,6}
if number of elements is odd in list.
list={1,2,3,4,5,6,7}
list1={1,2,3,4}
list2={5,6,7}
SOLUTION---
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
}*head;
int main()
{
struct node *temp;
int num,i,item,n;
scanf("%d",&num);
//creation of link list//
for(i=0;i<num;i++)
{
scanf("%d",&item);
if(i==0)
{
head=malloc(sizeof(struct node));
head->data=item;
temp=head;
}
else
{
temp->next=malloc(sizeof(struct node));
temp->next->data=item;
temp=temp->next;
}
}
temp->next=NULL;
struct node *firstend,*secondstrt,*secondend,*firststrt;
if(num%2==0)
n=num/2;
else
n=num/2+1;
temp=head;
for(i=1;i<=n;i++)
{
if(i==n)
firstend=temp;
temp=temp->next;
}
firststrt=head;
secondstrt=firstend->next;
firstend->next=NULL;
printf("first list\n");
while(firststrt!=NULL)
{
printf("%d ",firststrt->data);
firststrt=firststrt->next;
}
printf("\nsecond list\n");
while(secondstrt!=NULL)
{
printf("%d ",secondstrt->data);
secondstrt=secondstrt->next;
}
return 0;
}
example--
list-{1,2,3,4,5,6}
list1={1,2,3}
list2={4,5,6}
if number of elements is odd in list.
list={1,2,3,4,5,6,7}
list1={1,2,3,4}
list2={5,6,7}
SOLUTION---
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
}*head;
int main()
{
struct node *temp;
int num,i,item,n;
scanf("%d",&num);
//creation of link list//
for(i=0;i<num;i++)
{
scanf("%d",&item);
if(i==0)
{
head=malloc(sizeof(struct node));
head->data=item;
temp=head;
}
else
{
temp->next=malloc(sizeof(struct node));
temp->next->data=item;
temp=temp->next;
}
}
temp->next=NULL;
struct node *firstend,*secondstrt,*secondend,*firststrt;
if(num%2==0)
n=num/2;
else
n=num/2+1;
temp=head;
for(i=1;i<=n;i++)
{
if(i==n)
firstend=temp;
temp=temp->next;
}
firststrt=head;
secondstrt=firstend->next;
firstend->next=NULL;
printf("first list\n");
while(firststrt!=NULL)
{
printf("%d ",firststrt->data);
firststrt=firststrt->next;
}
printf("\nsecond list\n");
while(secondstrt!=NULL)
{
printf("%d ",secondstrt->data);
secondstrt=secondstrt->next;
}
return 0;
}
No comments:
Post a Comment