当我运行它时,它不会报告任何错误,但实际上什么也没有发生。它不会返回指向列表中最小元素的指针,它只是不执行任何操作。
创建一个带有指向 double 的第一个元素的指针的函数 链表,返回指向列表最小元素的指针
#include<stdio.h>
#include<stdlib.h>
typedef struct list DLlist;
struct list{
DLlist *next, *previous;
int number;
};
DLlist *first = NULL;
int n=0;
DLlist* add(DLlist *end, int number){
DLlist* perm;
perm = (DLlist *)malloc(sizeof(DLlist));
perm->number = number;
if(first==NULL){
first = perm;
first->next = NULL;
first->previous = NULL;
end = perm;
}else{
perm->next = NULL;
end->next = perm;
perm->previous = end;
end = perm;
return end;
n++;
}
}
DLlist* return_smallest(DLlist *first){
DLlist *max;
DLlist *current;
first = max;
current = first;
for(int i=0;i<n;i++){
if(current->number < max->number) max = current;
current = current->next;
}
return max;
}
void main(){
DLlist *end = NULL;
int number;
int choice;
do{
printf("1-Add elements to list: \n"
"2-Return a pointer to the smallest element in the list\n");
scanf("%d",&choice);
scanf("%d",&number);
switch(choice){
case 1: end = add(end, number);break;
case 2: printf("%d",(return_smallest(first))->number);
}
}while(choice == 1);
}
最佳答案
您的 end
var 是在 main()
中定义的,当您将其传递给 add
时,您实际上传递了该指针的副本,因此函数内部所做的更改不会复制回 main()
作用域中的变量。
c中通常的做法是将其地址(DLlist**
)传递给函数并将其用作双指针,因此更新将能够更新外部变量。
您还可以像 first
一样将 end
设置为全局,但这是一个坏习惯,因为它会阻止同时使用多个列表。最好避免全局变量,但它也能工作。
关于c - 双向链表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21561874/