7-52-两个有序链表序列的交集-编程题

7-52-两个有序链表序列的交集-编程题

解题代码

#include<stdio.h>
#include<stdlib.h>
typedef struct Node* List;
struct Node {
	int Data;
	List Next;
};
List Insert(List t, int num);
void Print(List head);
int main()
{
	List head1 = (List)malloc(sizeof(struct Node));
	head1->Next = NULL;
	List head2 = (List)malloc(sizeof(struct Node));
	head2->Next = NULL;
	List head3 = (List)malloc(sizeof(struct Node));
	head3->Next = NULL;
	int num;
	List t1 = head1, t2 = head2, t3 = head3;
	while (1) {
		scanf("%d", &num);
		if (num != -1) {
			t1 = Insert(t1, num);
		}
		else break;
	}
	while (1) {
		scanf("%d", &num);
		if (num != -1) {
			t2 = Insert(t2, num);
		}
		else break;
	}
	t1 = head1->Next; t2 = head2->Next;
	while (t1&&t2) {
		if (t1->Data<t2->Data) {
			t1 = t1->Next;
		}
		else if (t2->Data<t1->Data){
			t2 = t2->Next;
		}
		else {
			t3 = Insert(t3, t1->Data);
			t1 = t1->Next; t2 = t2->Next;
		}
	}
	Print(head3);
	return 0;
}

List Insert(List t, int num) {
	List new = (List)malloc(sizeof(struct Node));
	new->Data = num;
	new->Next = NULL;
	t->Next = new;
	t = new;
	return t;
}
void Print(List head) {
	List t = head->Next;
	int flag = 1;
	if (!t) printf("NULL");
	else {
		while (t) {
			if (flag) flag = 0;
			else printf(" ");
			printf("%d", t->Data);
			t = t->Next;
		}
	}
}

测试结果

在这里插入图片描述

问题整理

1.注意while循环体中控制循环结束条件的递进语句。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值