#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");
}
struct node *merge(struct node *head1,struct node *head2){/*链表合并后返回一个新链表*/
struct node *p3,*q1,*q2,*q3,*head3;
head3=create();
p3=head3;
q1=head1->next;
q2=head2->next;
while(q1&&q2){
q3=(struct node *)malloc(sizeof(struct node));/*分配新的结点空间来存储复制过来的数据*/
q3->next=NULL;
if(q1->data<=q2->data){
q3->data=q1->data;
p3->next=q3;
p3=q3;
if(q1->data==q2->data){
q2=q2->next;
}
q1=q1->next;
}else{
q3->data=q2->data;
p3->next=q3;
p3=q3;
q2=q2->next;
}
}
p3->next=q1?q1:q2;/*如果q1未空接q1,如果q1已空接q2*/
return head3;
}
int main(){
struct node *head1,*head2,*head3;
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");
head3=merge(head1,head2);
show(head3);/*合并后的链表为head3,打印head3即为合并后链表*/
return 0;
}
C语言实现顺序链表合并(此方法开辟新的节点空间来存储数据,原链表不被破坏,带头节点,两个原链表本身分别无重复元素)
最新推荐文章于 2023-07-12 23:03:38 发布