1、假设有两个按元素值递增次序排列的线性表,均以单链表形式存储。请编写算法将这两个单链表归并为一个按元素值递减次序排列的单链表,并要求利用原来两个单链表的结点存放归并后的单链表。
输入: 1 2 5 6 8
3 4 7 9 10
输出: 10 9 8 7 6 5 4 3 2 1
思路:利用尾插法,依次比较表头数据的大小,小的插入目标链表,而利用尾插法,即可倒置链表。
#include <iostream>
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct node
{
int data;
struct node *next;
} List;
List *CreateList() //创建链表,注意带头结点和不带头结点的区别
{
List *head,*cnew,*tail;
head = (List*)malloc(sizeof(List));
head->next = NULL;
int num;
while(1)
{
scanf("%d",&num);
if(num==0)break;
cnew = (List*)malloc(sizeof(List));
cnew->data = num;
cnew->next = NULL;
if(head->next==NULL)
head->next = cnew;
else
tail->next = cnew;
tail = cnew;
}
return head;
}
void showList(List *head)
{
List *p;
p = head->next;
while(p!=NULL)
{
printf("%d\t",p->data);
p = p->next;
}
}
List *List_merge(List *La,List *Lb)
{
List *p,*q,*r;
p = La->n