我应该为 2 个链表的交集创建一个链表。我为此编写的代码在交集列表的末尾显示了一个额外的元素 -> '0'。
struct ll{
int num;
struct ll *y;
};
typedef struct ll node;
void create(node *list){
char c;
printf("input: ");
scanf("%d", &list -> num);
printf("continue?(y/n)\t");
getchar(); c = getchar();
if(c == 'y'){
list -> y = (node *)malloc(sizeof(node));
create(list -> y); }
else list -> y = NULL;
}
void print(node *list){
if(list -> y != NULL){
printf("%d ->", list -> num);
if(list -> y -> y == NULL) printf("%d", list -> y -> num);
print(list -> y);
}
return;
}
int pres(node *list, int key){
if(list -> num == key) return 1;
else{
if(list -> y == NULL) return 0;
else pres(list -> y, key);
}
}
int count(node *list){
if(list -> y == NULL) return 1;
else return(1+count(list -> y));
}
gin(node *head1, node *head2, node *inter){
node *x = head2, *z = inter;
int n2, i;
n2 = count(head2);
for(i = 0; i<n2; i++){
if(pres(head1, head2 -> num)){
(inter -> num) = (head2 -> num);
inter -> y = (node *)malloc(sizeof(node));
inter = inter -> y; }
inter -> y = NULL;
head2 = head2 -> y;
}
head2 = x; inter = z;
}
main(){
node *head1, *head2, *inter;
head1 = (node *)malloc(sizeof(node));
head2 = (node *)malloc(sizeof(node));
inter = (node *)malloc(sizeof(node));
printf("enter list 1 elements:\n");
create(head1);
printf("\nenter list 2 elements:\n");
create(head2);
printf("\nlist1:\t");
print(head1);
printf("\nlist2:\t");
print(head2);
printf("\nintersection:\t");
gin(head1, head2, inter);
print(inter);
printf("\nno. of items in intersection list = %d\n", count(inter));
}
输入
输入列表 1 元素:
输入:20
继续?(y/n) 是
输入:30
继续?(y/n) 是
输入:40
继续?(y/n) 是
输入:60
继续?(y/n) n
输入列表 2 元素:
输入:10
继续?(y/n) 是
输入:30
继续?(y/n) 是
输入:50
继续?(y/n) 是
输入:60
继续?(y/n) n
输出
列表1:20 ->30 ->40 ->60
列表 2:10 ->30 ->50 ->60
交点:30 ->60 ->0
此时的问题
不。交集列表中的项目数 = 3