合并有序链表(输入输出)

#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;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值