#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *creat1(int a[],int n){
struct node *head,*tail,*s;
int i;
head = (struct node *)malloc(sizeof(struct node));
head->data=a[0];
head->next=NULL;
tail=head;
for (int i = 1; i < n; ++i) {
s=(struct node *)malloc(sizeof(struct node));
s->data = a[i];
s->next = NULL;
tail->next=s;
tail=s;
}
return head;
}
struct node *combine(struct node *p,struct node *q){
struct node *h,*t;
if(p->data<=q->data){
h=p;t=p;p=p->next;
}
else{
h=q;t=q;q=q->next;
}
while (p!=NULL && q!=NULL){
if (p->data<=q->data){
t->next=p;t=p;p=p->next;
} else{
t->next=q;t=q;q=q->next;
}
}
if (p==NULL)
t->next=q;
else
t->next=p;
return h;
}
void print(struct node *p){
while (p!=NULL){
printf("%d,",p->data);
p=p->next;
}
printf("\n");
}
int main(){
int a[10]={1,3,5,7,9,12,18,20,25,30},b[6]={4,6,10,12,14,230};
struct node *head,*head1,*head2;
printf("Creat list A:\n");
head1=creat1(a,10);
printf("Creat list B:\n");
head2=creat1(b,6);
printf("Output list A:\n");
print(head1);
printf("Output list B:\n");
print(head2);
printf("Combine list A and list B:\n");
head=combine(head1,head2);
printf("Output list after combine list A and list B:\n");
print(head);
return 0;
}
合并两个有序链表 押题卷
最新推荐文章于 2024-10-30 16:53:07 发布