簡體   English   中英

為什么這段代碼不起作用(發送列表作為參數)?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM