# Puzzle -- merging of two ordered linked list sequences (20 points) (comparison of two algorithms)

Keywords: Big Data encoding

7-18 merging of two ordered linked list sequences (20 minutes)

Given two non descending list sequences S1 and S2, the design function constructs a new non descending list S3 after the combination of S1 and S2.

### Input format:

The input is divided into two lines. Each line gives a non descending sequence composed of several positive integers. The end of the sequence is represented by − 1 (− 1 does not belong to this sequence). Numbers are separated by spaces.

### Output format:

Output a new non descending linked list after merging in a row. Separate the numbers with spaces. No extra spaces are allowed at the end. If the new linked list is empty, output NULL.

### Input example:

```1 3 5 -1
2 4 6 8 10 -1
```

### Output example:

`1 2 3 4 5 6 8 10`

Method 1: array representation

```#include<stdio.h>
#define N 500000
int main()
{
int a[N],b[N],c[N],asize=0,bsize=0,csize=0;
int temp,i=0,j=0,k;
while(scanf("%d",&temp)!=EOF&&temp!=-1)
{
a[asize++]=temp;
}
while(scanf("%d",&temp)!=EOF&&temp!=-1)
{
b[bsize++]=temp;
}
while(i<asize&&j<bsize)
{
if(a[i]<b[j])
{
c[csize++]=a[i];
i++;
}
else
{
c[csize++]=b[j];
j++;
}
}
if(i==asize)
{
for(k=j;k<bsize;k++)
{
c[csize++]=b[k];
}
}
else
{
for(k=i;k<asize;k++)
{
c[csize++]=a[k];
}
}
if(csize>0)
{
printf("%d",c[0]);
for(i=1;i<csize;i++)
{
printf(" %d",c[i]);
}
}
else printf("NULL");
}```

Advantages: simple and easy to understand, fast coding

Disadvantage: there will be a segment error in a big data test, only 16 points

Method 2: chain table representation

```#include<stdio.h>
#include<stdlib.h>
typedef struct Node *LNode;
typedef struct Node
{
int data;
LNode Next;
}Node;
{
int temp;
while(scanf("%d",&temp)!=EOF&&temp!=-1)
{
p=(LNode)malloc(sizeof(Node));
p->data=temp;
p->Next=NULL;
q->Next=p;
q=p;
}
}
{
LNode p1,p2,p3,q3;
while(p1&&p2)
{
if(p1->data<p2->data)
{
p3=(LNode)malloc(sizeof(Node));
p3->data=p1->data;
p3->Next=NULL;

q3->Next=p3;
q3=p3;
p1=p1->Next;
}
else
{
p3=(LNode)malloc(sizeof(Node));
p3->data=p2->data;
p3->Next=NULL;

q3->Next=p3;
q3=p3;
p2=p2->Next;
}
}

if(p1)
{
while(p1)
{
p3=(LNode)malloc(sizeof(Node));
p3->data=p1->data;
p3->Next=NULL;

q3->Next=p3;
q3=p3;
p1=p1->Next;
}
}
else
{
while(p2)
{
p3=(LNode)malloc(sizeof(Node));
p3->data=p2->data;
p3->Next=NULL;

q3->Next=p3;
q3=p3;
p2=p2->Next;
}
}
}
{
LNode p3;
if(!p3) printf("NULL");
else
{
printf("%d",p3->data);
p3=p3->Next;
}
while(p3)
{
printf(" %d",p3->data);
p3=p3->Next;
}
}
int main()
{