我有一个简单的程序,它初始化一个列表并向其中添加 n 个元素。问题是它不能添加下一个 n-1 元素(它只是用第一个元素初始化列表)。我测试了条件,似乎问题last->next=elem
出在add_elem
功能上。这是程序:
#include <stdio.h>
#include <stdlib.h>
typedef struct lista {
int val;
struct lista *next;
} list;
void allocate(list *p) {
printf("Alocating memory...");
p=(list *)malloc(sizeof(list));
if(p==NULL) {
printf("Failed! Exiting program...");
exit(1);
} else printf("Done! \n");
}
void init_list(list *first, list *last) {
printf("Insert first element value: ");
scanf("%d", &(first->val));
printf("Initializing list...\n");
allocate(first);
first->next=NULL;
last=first;
if(first->next==NULL && last==first) {
printf("Done initializing! \n");
printf("Last value: %d\n", last->val);
}
}
void add_elem(list *elem, list *last, int i) {
printf("Insert the %dth element value: ",i);
scanf("%d", &elem->val);
printf("Adding element to list...\n");
allocate(elem);
elem->next=NULL;
last->next=elem;
last=elem;
if(elem->next==NULL && last==elem && last->next==elem) {
printf("Done adding! \n");
printf("Last value: %d\n", last->val);
}
//printf("%d\n", first->next->val);
}
void print_list(list *first) {
printf("\nCurrent list: \n");
list *it;
for(it=first;it!=NULL;it=it->next) {
printf("%d ",it->val);
}
}
int main() {
list first, last, elem;
int n,i;
printf("Insert number of elements: ");
scanf("%d",&n);
init_list(&first,&last);
for(i=2;i<=n;i++) {
add_elem(&elem,&last,i);
}
print_list(&first);
return 0;
}