#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode {
ElemType Data;
struct LNode * Next;
}LNode, *List;
List CreateList() {
List head, L, pro;
int n;
L = (List)malloc(sizeof(struct LNode));
head = L;
scanf("%d", &n);
if (n == -1)
{
L = NULL;
return L;
}
while (1)
{
if (n == -1)
{ //序列结束符号
pro->Next = NULL; //序列尾指向NULL
free(L); //释放多余节点
return head;
}
L->Data = n;
L->Next = (List)malloc(sizeof(LNode));
pro = L;
L = L->Next;
scanf("%d", &n);
}
}
List CombineList(List L1, List L2)
{
List L, head;
L = (List)malloc(sizeof(LNode));
head = L;// 建立新节点
while (L1&&L2)
{
// 进行挨个比较
if (L1->Data <= L2->Data)
{
L->Next = L1;
L = L->Next;
L1 = L1->Next;
}
else
{
L->Next = L2;
L = L->Next;
L2 = L2->Next;
}
}
if (L1) // L2进行到空或者L2初始为空
{
L->Next = L1;
L = head;
head = head->Next;
free(L);
return head;
}
else if (L2) // L1进行到空或者L1初始为空
{
L->Next = L2;
L = head;
head = head->Next;
free(L);
return head;
}
else //两者初始皆为空
return NULL;
}
int main() {
List L, L1, L2;
int m, n, i;
L1 = CreateList();
L2 = CreateList();
L = CombineList(L1, L2);
if (!L)
printf("NULL"); //链表为空时输出NULL
else
{
while (L->Next)
{
printf("%d ", L->Data);
L = L->Next;
}
printf("%d", L->Data);
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef struct Node{
int data;
struct node *next;
}LinkList,*List;
List CreatList(){
List head,l,node;
int n;
l=(List)malloc(sizeof(struct Node));
head=l;
cin>>n;
if(n==-1){
l=NULL;
return head;
}
else{
if(n==-1){
node->next=NULL;
free(l);
return head;
}
l->next=(List)malloc(sizeof(struct Node));
l->data=n;
node=l;
l=l->next;
cin>>n;
}
}
List CombineList(List L1,List L2){
List head,l;
l=(List)malloc(sizeof(struct Node));
head=l;
while(L1&&L2){
if(L1->data<=L2->data){
l->next=L1;
l=l->next;
L1=L1->next;
}
else{
l->next=L2;
l=l->next;
L2=L2->next;
}
}
else{
if(L1)//L2为空
{
l->next=L1;
l=head;
head=head->next;
free(l);
}
if(L2)
{
l->next=L2;
l=head;
head=head->next;
free(l);
}
else{
return NULL;
}
}
}
int main(){
List L,L1,L2;
int m,n,i;
L1=CreatList();
L2=CreatList();
L=CombineList(L1,L2);
if (!L)
printf("NULL");
else
{
while (L->Next)
{
printf("%d ", L->Data);
L = L->Next;
}
printf("%d", L->Data);
}
}