1

此代码仅在列表末尾添加一个元素(仅创建头元素,之后没有任何内容)。我的程序有什么问题?我应该在函数中传递两个项目,头部和项目还是只传递一个?

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct MyList
{
    int x;
    int y;
    struct MyList * next;
}List;

typedef List * Item;

void AddEnd(Item * head);
void PrintList(Item * head);

int main(void)
{
    int response;
    Item head;
    head = NULL;
    while(1)
    {
        printf("1- Print, 2 - Add to End, 3 - exit\n");
        scanf("%d", &response);
        switch(response)
        {
            case 1: PrintList(&head); break;
            case 2: AddEnd(&head); break;
            case 3: return 0;
        }       
    }    
    return 0;
}

void PrintList(Item * head)
{
    Item temp;
    temp = *head;
    while(temp != NULL)
    {
        printf("%d %d\n", temp->x, temp->y);
        temp = temp->next;
    }
}

void AddEnd(Item * head)
{
    Item new, temp;
    new = (Item)malloc(sizeof(new));
    printf("Enter x and y: ");
    scanf("%d %d", &new->x, &new->y);
    new->next = NULL;
    if(*head == NULL)
    {
        *head = new;
    }
    else
    {
        temp = *head;
        while(temp != NULL)
        {
            temp = temp->next;
        }

        temp = new;
    }

}

我刚刚尝试过的这段代码也不起作用:

void AddEnd(Item * head, Item * item)
{
    Item new, temp;
    new = (Item)malloc(sizeof(new));
    printf("Enter x and y: ");
    scanf("%d %d", &new->x, &new->y);
    new->next = NULL;
    if(*head == NULL)
    {
        *head = new;
    }
    else
    {
        temp = *head;
        while(temp != NULL)
        {
            temp = temp->next;
        }

        temp = new;
        *item = temp;
    }
}
4

2 回答 2

2

在子句中的AddEnd函数中else,当您退出 while 循环时,temp是 now NULL。但是,它之前的元素仍然指向NULL.

尝试类似的东西

temp = *head;
if (temp->next == NULL) {
    temp->next = new;
} else {
    while((temp->next) != null) {
        temp = temp->next;
    }
    temp->next = new;
}

在你的else条款中。

(这,以及您对其他人引用的 malloc 的理解的明显问题new应该是 aItem *并且 malloc 调用应该是malloc(sizeof(Item))。您也不需要强制转换 malloc 的返回值(实际上,如果你做)。)更仔细地阅读你的 typedef,实际上new 应该Item是一个(因为它是一个指向结构的指针List并且你有typedef List* Item)。尝试new = malloc(sizeof(List));并声明new为 type List *。(这typedef List * Item使您的代码难以阅读;不清楚什么是指针,什么不是。)

于 2013-08-03T00:36:05.507 回答
0

你需要改变这个:

new = (Item)malloc(sizeof(new));

对此:

new = (Item *)malloc(sizeof(List));

希望这可以帮助

于 2013-08-03T00:36:24.703 回答