Я не знаю, почему мой указатель на связанный список не двигается - PullRequest
0 голосов
/ 03 декабря 2018

Я пытаюсь написать фрагмент кода, который добавляет элементы в список.

typedef struct things {
    int value;
    struct things *next;
} something;


int main()
{
    int input = 0;
    something *head = NULL;
    something *current = NULL;
    current = head; //current points to head address
    while(input != -1)
    {
        scanf("%d", &input);
        while(current != NULL) //loop until current node returns NULL
        {
            current = current->next; //go to next node
        }

        current = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
        current->value = input;
        current->next = NULL; //next points to NULL
    }
    current=head; //current points back to head
    while(current != NULL)
    {
        printf("%d -> ", current->value);
        current = current->next;
    }
    puts("NULL");

    return 0;
}

, когда я пытаюсь распечатать список, однако, я не получаю вывод.Так что даже если я введу 1 2 3 4..etc, функция печати ничего не выводит

while(current != NULL)
{
    printf("%d -> ", current->value);
    current = current->next;
}
puts("NULL");

Я ожидаю вывод наподобие 1 -> 2 -> 3 -> ... 9 -> NULL.Я только начал узнавать о связанных списках, поэтому любые советы приветствуются.

Ответы [ 2 ]

0 голосов
/ 03 декабря 2018

Ваш текущий подход не подходит для одного указателя.Где выделение памяти для current не будет вставлять узел в список.

Просто сделав current указателем на указатель, как показано ниже, ваш подход будет работать.

int input = 0;
something *head = NULL;
something **current = NULL;
current = &head; //current points to head address
while(input != -1)
{
    scanf("%d", &input);
    while(*current != NULL) //loop until current node returns NULL
    {
        current = &(*current)->next; //go to next node
    }

    *current = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
    (*current)->value = input;
    (*current)->next = NULL; //next points to NULL
}
current=&head; //current points back to head
while(*current != NULL)
{
    printf("%d -> ", (*current)->value);
    current = &(*current)->next;
}
puts("NULL");
0 голосов
/ 03 декабря 2018

Вы ни в коем случае не обновляете значение head.Или укажите последний узел в списке на вновь созданный.

Проверьте, установлен ли сначала head, и, если нет, заполните его.В противном случае найдите последний узел списка и добавьте новый к нему в качестве «следующего», как показано ниже.

if(head == NULL)
{
    head = malloc(sizeof(something));
    head->value = input;
    head->next = NULL; //next points to NULL
}
else
{
    current = head;
    while(current->next != NULL) //loop until current node returns NULL
    {
        current = current->next; //go to next node
    }

    current->next = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
    current->next->value = input;
    current->next->next = NULL; //next points to NULL
}
...