#include<stdio.h>
#include<stdlib.h>
//实现合并两个链表
//建立链表
struct listNode{
int val;
struct listNode *next;
};
//合并两个有序链表
struct listNode* makeTwoList(struct listNode* pHead1,struct listNode* pHead2)
{
if(pHead1 == NULL){
return pHead2;
}
if(pHead2 == NULL){
return pHead1;
}
if(pHead1->val <= pHead2->val){
pHead1->next = makeTwoList(pHead1->next,pHead2);
return pHead1;
}else{
pHead2->next = makeTwoList(pHead1,pHead2->next);
return pHead2;
}
}
//打印出链表
void print_list(struct listNode* head)
{
printf("最后的结果为:\n");
while(head!=NULL){
printf("%d",head->val);
head=head->next;
}
printf("\n");
}
//处理链表的输入
struct listNode* input_List(void){
int n,val;
struct listNode* phead = (struct listNode*)malloc(sizeof(struct listNode));
struct listNode* new=phead;
printf("请输入链表的长度\n");
scanf("%d",&n);//接收输入的链表长度
printf("请输入链表的元素用空格隔开\n");
for(int i=1;i<=n;i++){
scanf("%d",&val);
//如果接收到的链表的节点只有一个的话那就是他本身
if(i==1){
new->val=val;
new->next=NULL;
}
//如果接收到的链表节点不是一个的话,那就建立一个新的链表p,将每个收到的节点作为链表p的节点保存起来
else{
struct listNode* p = (struct listNode*)malloc(sizeof(struct listNode));
p->val=val;
p->next=NULL;
new->next=p;
new=p;
}
}
return phead;
}
int main()
{
struct listNode* head1=input_List();
struct listNode* head2=input_List();
struct listNode* new=makeTwoList(head1,head2);
print_list(new);
return 0;
}
合并有序链表(输入输出)
最新推荐文章于 2022-12-08 23:25:36 发布