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循环体中控制循环结束条件的递进语句。
发布了47 篇原创文章 · 获赞 2 · 访问量 1341

猜你喜欢

转载自blog.csdn.net/Aruasg/article/details/105042741