Description
假设两个按元素值非递减有序排列的线性表A和B,均以单链表作为存储结构,试编写程序,将A表和B表归并成一个按元素值非递增有序排列的线性表C,并要求利用原表(即A表和B表的)结点空间存放表C。
Input
第一行输入两个正整数m,n(m,n<=100),用空格分开,分别表示线性表A和B中元素个数,其后两行分别输入单链表A和B。
Output
输出单链表C。
-
Sample Input
5 5 1 3 7 12 16 2 6 7 13 20
-
Sample Output
20 16 13 12 7 7 6 3 2 1
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int num;
node* next;
}node;
node* init(int x){
int i;
node *head,*p,*q;
head=(node*)malloc(sizeof(node));
q=head;
while(x--){
p=(node*)malloc(sizeof(node));
scanf("%d",&(p->num));
q->next=p;
q=p;
}
q->next=NULL;
return head;
}
node* unio(node* x,node* y){
node *p,*q,*t,*r,*head;
head=(node*)malloc(sizeof(node));
r=head;
p=x->next;
q=y->next;
while(p&&q){
if(p->num < q->num){
r->next=p;
r=p;
p=p->next;
}
else{
r->next=q;
r=q;
q=q->next;
}
}
if(p){
r->next=p;
r=p;
p=p->next;
}
else if(q){
r->next=q;
r=q;
q=q->next;
}
else{
r->next=NULL;
}
return head;
}
node* down(node* head){
node *p,*q;
p=head->next;
head->next=NULL;
while(p){
q=p;
p=p->next;
q->next=head->next;
head->next=q;
}
q=head->next;
return head;
}
int main(){
int n,m,k,i;
node *head1,*head2,*p,*q,*r,*t;
scanf("%d%d",&n,&m);
head1=init(n);
head2=init(m);
head1=unio(head1,head2);
head1=down(head1);
r=head1->next;
while(r){
if(r->next==NULL){
printf("%d\n",r->num);
}
else{
printf("%d ",r->num);
}
r=r->next;
}
return 0;
}
复习:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}node,*pnode;
void init(pnode head, int x){
int i;
pnode g, t;
g = head;
for(i = 0; i < x; i++){
t = (pnode)malloc(sizeof(node));
scanf("%d", &t->data);
g->next = t;
g = t;
}
g->next = NULL;
}
void insert(pnode head1, pnode head2){
pnode p, q, r;
p = head1->next;
q = head2->next;
r = head1;
while(p&&q){
if(p->data < q->data){
r->next = p;
r = p;
p = p->next;
}
else{
r->next = q;
r = q;
q = q->next;
}
}
while(p){
r->next = p;
r = p;
p = p->next;
}
while(q){
r-> next = q;
r = q;
q = q->next;
}
r->next = NULL;
}
void invlink(pnode head){
pnode g, t;
g = head->next;
head->next = NULL;
while(g){
t = g;
g = g->next;
t->next = head->next;
head->next = t;
}
}
void output(pnode head){
pnode g;
g = head->next;
while(g->next){
printf("%d ", g->data);
g = g->next;
}
printf("%d\n", g->data);
}
int main(){
int m, n;
pnode head1, head2;
head1 = (pnode)malloc(sizeof(node));
head2 = (pnode)malloc(sizeof(node));
scanf("%d%d", &m, &n);
init(head1, m);
init(head2, n);
insert(head1, head2);
invlink(head1);
output(head1);
}