已知有序单链表a、b,将a、b进行合并,要求合并后的单链表c中的元素按非递增有序排列
思路:使用单链表的表头插入元素即可,有序递增就会变成有序递减
/*
* 将有序递增的单链表a、b合并成为有序递减的单链表c
* */
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
void IniteList(LinkList &list);
void InsertList(LinkList &list, int e);
void Traverse(LinkList &list);
void Conjunction(LinkList &a,LinkList &b,LinkList &c);
int main()
{
LinkList a,b,c;
int m,n;
IniteList(a);
printf("请输入链表a中元素的个数:");
scanf("%d",&m);
printf("\n请逐个输入链表a中的元素:");
for (int i = 0; i < m; ++i)
{
int e;
scanf("%d",&e);
InsertList(a,e);
}
printf("\n链表a中的元素分别为:");
Traverse(a);
IniteList(b);
printf("\n请输入链表b中元素的个数:");
scanf("%d",&n);
printf("\n请逐个输入链表b中的元素:");
for (int i = 0; i < m; ++i)
{
int e;
scanf("%d",&e);
InsertList(b,e);
}
printf("\n链表b中的元素分别为:");
Traverse(b);
IniteList(c);
Conjunction(a,b,c);
printf("\n链表c中的元素分别为:");
Traverse(c);
}
void IniteList(LinkList &list)
{
list = (LinkList)malloc(sizeof(LNode));
if(!list)
{
printf("OVERFLOW");
return ;
}
list->next = NULL;
}
void InsertList(LinkList &list,int e)
{
LinkList tail = list;
LinkList p;
p = (LinkList)malloc(sizeof(LNode));
if(!p)
{
return ;
}
while(tail->next)
tail = tail->next;
p->data = e;
p->next = tail->next;
tail->next = p;
}
void Traverse(LinkList &list)
{
LinkList t = list;
while(t->next)
{
printf("%-3d",t->next->data);
t = t->next;
}
}
void Conjunction(LinkList &a,LinkList &b,LinkList &c)
{
if(!a || !b || !c)
return ;
LinkList x,y,z;
x = a->next;
y = b->next;
z = c;
LinkList s;
LinkList remain;
while(x && y)
{
if(x->data < y->data)
{
s = x;
x = x->next;
}
else
{
s = y;
y = y->next;
}
s->next = z->next;
z->next = s;
}
if(x)
remain = x;
else
remain = y;
while(remain)
{
s = remain;
remain = remain->next;
s->next = z->next;
z->next = s;
}
}