【问题标题】:why this code didn't work(send list as argument)?为什么这段代码不起作用(发送列表作为参数)?
【发布时间】:2021-04-20 18:50:39
【问题描述】:

代码编译没有错误,但执行时却没有显示正确的结果。这里的问题与指针有关吗?特别是发送列表作为参数。 谁能帮帮我,我很困惑,谢谢...

#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);

}
 ``

【问题讨论】:

  • 说它不起作用没有任何帮助。您的逻辑在add() 中似乎存在缺陷。另外,请注意释放您分配的内存。最好使用 gdb。
  • 哲学也无济于事

标签: c pointers linked-list


【解决方案1】:
#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);
}

【讨论】:

  • 我希望你明白你的错误在哪里:)
  • 是的,我完全理解你写的东西......再次感谢你......使用指向单元格的指针这是一个完美的选择
猜你喜欢
  • 2010-09-18
相关资源
最近更新 更多