[英]why this code didn't work(send list as argument)?
代码编译没有错误,但执行时没有显示正确的结果。 这里的问题与指针有关吗? 特别是发送列表作为参数。 谁能帮帮我,我很困惑,谢谢...
#include <stdio.h>
#include <stdlib.h>
typedef int Element;
typedef struct cell{
Element val;
struct cell* next;
} cell ;
typedef struct List{
cell *first;
}List;
void add(List *l, Element e)
{
List* a=l;
cell*nve=(cell*)malloc(sizeof(cell));
nve->val=e;
nve->next=NULL;
if(a->first==NULL)
{
l->first->val=nve;
}
else
{
while(a->first!=NULL)
{
a->first=a->first->next;
}
a->first->next=nve;
}
}
void display(List *l){
List *a=l;
while(a->first!=NULL)
{
printf("%d\n",a->first->val);
a->first=a->first->next;
}
}
int main()
{
List *x=(List*)malloc(sizeof(List));
add(x,15);
add(x,16);
display(x);
}
``
#include <stdio.h>
#include <stdlib.h>
typedef struct cell {
int val;
struct cell *next;
} cell;
typedef struct List {
cell *first;
} List;
void add(List *l, int e) {
cell *nve = (cell *) malloc(sizeof(cell));
nve->val = e;
nve->next = NULL;
cell *ptr = l->first;
if (l->first == NULL) {
l->first = nve;
} else {
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = nve;
}
}
void display(List *l) {
cell *ptr = l->first;
while (ptr != NULL) {
printf("%d\n", ptr->val);
ptr = ptr->next;
}
}
int main() {
List *l = (List *) malloc(sizeof(List));
l->first = NULL;
add(l, 15);
add(l, 16);
add(l, 17);
display(l);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.