Experiment 11-2-5 Linked List Splicing
Given two non-descending linked list sequences S1 and S2, the design function constructs a new non-descending linked list S3 that is merged with S1 and S2.
Input format:
The input is divided into two lines. Each line gives a non-descending sequence composed of several positive integers. Use −1 to indicate the end of the sequence (−1 does not belong to this sequence). The numbers are separated by spaces.
Output format:
Output the new non-descending linked list after merging in one line, separated by spaces between numbers, and no extra spaces at the end; if the new linked list is empty, output NULL.
Input sample:
1 3 5 -1
2 4 6 8 10 -1
Sample output:
1 2 3 4 5 6 8 10
Although other methods are here to kill the linked list, but after all, it is a question of investigating the linked list, and it is still solved by the linked list in a proper way.
AC code
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *build();
struct Node *print(struct Node *a,struct Node *b);
int main()
{
struct Node *a,*b,*c;
a=build();
b=build();
c=print(a,b);
if(!c)
printf("NULL\n");
while(c)
{
if(c->next==NULL)
printf("%d",c->data);
else
printf("%d ",c->data);
c=c->next;
}
}
struct Node *build()
{
int a;
struct Node *head=NULL,*str=NULL;
scanf("%d",&a);
while(a!=-1)
{
struct Node *p=(struct Node*)malloc(sizeof(struct Node));
p->data=a;
p->next=NULL;
if(head==NULL)
head=p;
else
str->next=p;
str=p;
scanf("%d",&a);
}
return head;
}
struct Node *print(struct Node *a,struct Node *b)
{
struct Node *head=NULL,*str=NULL;
while(a&&b)
{
if(a->data<b->data)
{
if(head==NULL)
head=a;
else
str->next=a;
str=a;
a=a->next;
}
else
{
if(head==NULL)
head=b;
else
str->next=b;
str=b;
b=b->next;
}
}
if(a)
while(a)
{
if(head==NULL)
head=a;
else
str->next=a;
str=a;
a=a->next;
}
if(b)
{
while(b)
{
if(head==NULL)
head=b;
else
str->next=b;
str=b;
b=b->next;
}
}
return head;
}