#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct Node{
int Data;
struct Node *next;
};
struct Node *create(){
struct Node *head;
head=(struct Node *)malloc(sizeof(struct Node));
head->next=NULL;
return head;
}
void Sq_insert(struct Node *head,int num){
struct Node *p,*q;
p=head;
while(p->next!=NULL&&p->next->Data<num){
p=p->next;
}
q=(struct Node *)malloc(sizeof(struct Node));
q->Data=num;
q->next=p->next;
p->next=q;
}
void show(struct Node *head){
struct Node *p;
p=head->next;
int count=0;
while(p){
printf("%d\t",p->Data);
count++;
if(count%10==0){
printf("\n");
}
p=p->next;
}
printf("\n");
}
void merge(struct Node *head1,struct Node *head2){/*合并后链表头指针为head1*/
struct Node *p1,*q1,*q2;
p1=head1;
q1=head1->next;
q2=head2->next;
while(q1&&q2){
if(p1!=head1&&p1->Data==q1->Data){
q1=q1->next;
}else if(p1!=head1&&p1->Data==q2->Data){
q2=q2->next;
}else if(q1->Data<q2->Data){
p1->next=q1;
p1=q1;
q1=q1->next;
}else if(q1->Data>q2->Data){
p1->next=q2;
p1=q2;
q2=q2->next;
}else{
p1->next=q1;
p1=q1;
q1=q1->next;
q2=q2->next;
}
}
if(q1==NULL){
while(q2){
if(p1!=head1&&p1->Data==q2->Data){
q2=q2->next;
}else{
p1->next=q2;
p1=q2;
q2=q2->next;
}
}
}else{
while(q1){
if(p1!=head1&&p1->Data==q1->Data){
p1=p1->next;
}else{
p1->next=q1;
p1=q1;
q1=q1->next;
}
}
}
p1->next=NULL;
}
int main(){
struct Node *head1,*head2;
head1=create();
head2=create();
for(int i=0;i<20;i++){
Sq_insert(head1,rand()%15);
Sq_insert(head2,rand()%15);
}
printf("链表一:\n");
show(head1);
printf("链表二:\n");
show(head2);
merge(head1,head2);
printf("合并后链表:\n");
show(head1);
return 0;
}
08-01
1077
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交