#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;
while(p!=NULL){
printf("%d\t",p->data);
p=p->next;
}
printf("\n");
}
void merge(struct node *head1,struct node *head2){/*以head1作为合并后的链表的头节点*/
struct node *p1,*q1,*q2,*temp;
p1=head1;
q1=head1->next;
q2=head2->next;
while(q1&&q2){
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;
temp=q2;
q2=q2->next;
free(temp);
}
}
p1->next=q1?q1:q2;/*如果q1未空接q1,如果q1已空接q2*/
}
int main(){
struct node *head1,*head2;
head1=create();
head2=create();
srand(time(NULL));/*随机数种子*/
for(int i=0;i<6;i++){
Sq_insert(head1,rand());/*随机插入数据*/
Sq_insert(head2,rand());
}
show(head1);
show(head2);
printf("\n\n");
merge(head1,head2);
show(head1);/*合并后链表合到了head1,打印head1即为合并后链表*/
return 0;
}
C语言实现顺序链表的合并(此方法不开辟新的空间,在原链表上操作,带头节点,两个原链表本身分别无重复元素)
最新推荐文章于 2022-04-08 21:39:35 发布