Не может пройти через связанный список C - PullRequest
0 голосов
/ 13 июня 2018

Задача - создать связанный список, состоящий из объектов.Пользователь вводит данные для каждого отдельного Node в main, а затем объект передается в push, который создает список.

Проблема возникает в функции printList, где условиеза break никогда не встречался.По какой-то причине строка head = head->next ничего не делает, так как адрес next при каждой итерации остается неизменным.

typedef struct Node {
    int a;
    char asd[30];
    struct Node *next;
}Node;

Node *head = NULL;

void push(Node**head, struct Node* object);
void printList(Node *head);

int main() {

    struct Node {
        int oA;
        char oAsd[30];
        struct Node *next;
    };

    struct Node *object = malloc(sizeof(struct Node));

    int c = 0;
    while (1) {
        printf("This int will be stored in Node %d.\n", ++c);
        scanf("%d", &object->oA);
        getchar();
        if (!object->oA) {
            break;
        }
        printf("This string will be stored in Node %d.\n", c);
        gets_s(object->oAsd, 30);
        if (!(strcmp(object->oAsd, "\0"))) {
            break;
        }
        push(&head, object);
    }
    printList(head);

    return 0;
}

void push(Node ** head,  struct Node* object)
{
    Node *tmp = malloc(sizeof(Node));
    tmp = object;
    tmp->next = (*head);
    (*head) = tmp;
}


void printList(Node *head) {
    if (head == NULL) {
        puts("No list exists.");
        exit(9);
    }

        while (1) {
            printf("-------------------------------\n");
            printf("|Int: <%d> |||| String: <%s>.|\n", head->a, head->asd);
            printf("-------------------------------\n");
            if (head->next) {
                printf("\n\n%p\n\n", head->next);

                head = head->next;
            }
            else {
                break;
            }
        }
}`

1 Ответ

0 голосов
/ 13 июня 2018

В вашем коде есть две основные проблемы:

  • Вы определяете struct Node как снаружи main, так и внутри main

  • Здесь tmp = object; вы копируете значение указателя в другой указатель, но вы действительно хотите скопировать значение структуры в другую структуру, т.е. *tmp = *object;.

Кроме того -не помещайте head в качестве глобальной переменной.

Поэтому код должен быть больше похож на:

typedef struct Node {
    int a;
    char asd[30];
    struct Node *next;
}Node;

void push(Node**head, struct Node* object);
void printList(Node *head);

int main() {
    Node *head = NULL;

    struct Node *object = malloc(sizeof(struct Node));

    int c = 0;
    while (1) {
        printf("This int will be stored in Node %d.\n", ++c);
        scanf("%d", &object->a);
        getchar();
        if (!object->a) {
            break;
        }
        printf("This string will be stored in Node %d.\n", c);
        gets_s(object->asd, 30);
        if (!(strcmp(object->asd, "\0"))) {
            break;
        }
        push(&head, object);
    }
    printList(head);

    return 0;
}

void push(Node ** head,  struct Node* object)
{
    Node *tmp = malloc(sizeof(Node));
    *tmp = *object;                    // Copy the struct
    tmp->next = (*head);
    (*head) = tmp;
}


void printList(Node *head) {
    if (head == NULL) {
        puts("No list exists.");
        exit(9);
    }

        while (1) {
            printf("-------------------------------\n");
            printf("|Int: <%d> |||| String: <%s>.|\n", head->a, head->asd);
            printf("-------------------------------\n");
            if (head->next) {
                printf("\n\n%p\n\n", head->next);

                head = head->next;
            }
            else {
                break;
            }
        }
}
...