欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-07 21:44:28
...

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

测试结果

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

问题整理

1.注意while循环体中控制循环结束条件的递进语句。