Добавить связанный список элементов - PullRequest
0 голосов
/ 07 мая 2020
#include <stdio.h>
#include <stdlib.h>

typedef struct str_node {
    int data;
    struct str_node *next;
} node;

void create_list(node ** head, int n);
void display_list(node * head);
void add_e(node ** head);

int
main(void)
{
    int n;
    node *head;

    head = NULL;
    printf("Insert size of list: ");
    scanf("%d",&n);

    create_list(&head, n);
    display_list(head);
    add_e(&head);
    display_list(head);

    return 0;
}

void
display_list(node *head)
{
    if (head == NULL) {
        printf("Empty list.");
    }
    else {
        while (head != NULL) {
            printf("DATA: %d\n", head->data);
            head = head->next;
        }
        puts("null");
    }
}




void create_list(node **head,int n){
    node *new,*tmp;
    int num,i;
    *head = malloc(sizeof(node));
    if(*head == NULL){
        printf("Memory can not be allocated.");
    }
    else{
        printf("Insert element 1: ");
        scanf("%d",&num);
        (*head)->data = num;
        (*head)->next = NULL;
        tmp = *head;

        for(i=2;i<=n;i++){
            new = malloc(sizeof(node));
            if(new == NULL){
                printf("Memory can not be allocated.");
                break;
            }
                else{
                printf("Insert element %d: ",i);
                scanf("%d",&num);
                new->data = num;
                new->next = NULL;
                tmp->next = new;
                tmp = tmp->next;
            }
        }
    }
}


void
add_e(node **head)
{
    node *new;
    int num;

    new = malloc(sizeof(node));
    if (new == NULL) {
        printf("Memory can not be allocated.");
    }
    else {
        printf("Insert element at the beginnig: ");
        scanf("%d", &num);
        new->data = num;
        new->next = NULL;
        while ((*head)->next != NULL) {
            *head = (*head)->next;
        }
        (*head)->next = new;
    }
}

Я не понимаю, почему после использования функции add_e() функция display_list() выдает мне только два последних числа в списке. Функция add_e() должна добавлять элемент в конец списка. Что я делаю не так?

Изменить: добавлена ​​функция create_list(), чтобы вы могли лучше понять, но теперь мне предлагается добавить больше деталей, поэтому я что-то пишу.

1 Ответ

2 голосов
/ 07 мая 2020

В main, n является унифицированным , поэтому вы получите случайные / плохие результаты.

add_e следует не использовать *head в while или даже while. printf говорит «вставить в начало», что отличается / проще. Это то, что я сейчас закодировал / исправил.

Вы бы хотели использовать al oop, , если вы [действительно] хотели вставить / добавить к конец списка. Но l oop все равно будет неверным, потому что вы не хотите продвигаться head при нахождении конца.

Я также исправил printf для запросы и scanf

Вот отредактированная / исправленная версия вашего кода с аннотациями ошибок:

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

typedef struct str_node {
    int data;
    struct str_node *next;
} node;

void create_list(node **head, int n);
void display_list(node *head);
void add_e(node ** head);

int
main(void)
{
    int n;
    node *head;

    head = NULL;

// NOTE/BUG: n is unitialized
#if 1
    n = 5;
#endif
    create_list(&head, n);
    display_list(head);

    add_e(&head);
    display_list(head);

    return 0;
}

void
display_list(node *head)
{
    if (head == NULL) {
        printf("Empty list.");
    }
    else {
        while (head != NULL) {
            printf("DATA: %d\n", head->data);
            head = head->next;
        }
        puts("null");
    }
}

void
create_list(node **head, int n)
{
    node *new,
    *tmp;
    int num,
     i;

    *head = malloc(sizeof(node));
    if (*head == NULL) {
        printf("Memory can not be allocated.");
    }
    else {
        printf("Insert element 1: ");
#if 1
        fflush(stdout);
#endif
#if 0
        scanf("%d", &num);
#else
        scanf(" %d", &num);
#endif

        (*head)->data = num;
        (*head)->next = NULL;
        tmp = *head;

        for (i = 2; i <= n; i++) {
            new = malloc(sizeof(node));
            if (new == NULL) {
                printf("Memory can not be allocated.");
                break;
            }
            else {
                printf("Insert element %d: ", i);
#if 1
                fflush(stdout);
#endif
#if 0
                scanf("%d", &num);
#else
                scanf(" %d", &num);
#endif
                new->data = num;
                new->next = NULL;
                tmp->next = new;
                tmp = tmp->next;
            }
        }
    }
}

void
add_e(node **head)
{
    node *new;
    int num;

    new = malloc(sizeof(node));
    if (new == NULL) {
        printf("Memory can not be allocated.");
    }
    else {
        printf("Insert element at the beginnig: ");
        fflush(stdout);
        scanf(" %d", &num);

        new->data = num;
        new->next = NULL;

#if 0
        while ((*head)->next != NULL) {
            *head = (*head)->next;
        }
        (*head)->next = new;
#else
        if (*head == NULL)
            *head = new;
        else {
            new->next = *head;
            *head = new;
        }
#endif
    }
}

ОБНОВЛЕНИЕ:

В add_e, поскольку я не мог быть уверен, хотите ли вы вставить в начало списка [на основе printf] или в конец [на основе кода], я создал версию, которая очищена от немного больше и демонстрирует оба типа:

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

typedef struct str_node {
    int data;
    struct str_node *next;
} node;

void create_list(node **head, int n);
void display_list(node *head);
void add_begin(node **head);
void add_end(node **head);

int
main(void)
{
    int n;
    node *head;

    setbuf(stdout,NULL);

    head = NULL;

    printf("Enter initial number of list elements: ");
    scanf(" %d",&n);

    create_list(&head, n);
    display_list(head);

    add_begin(&head);
    display_list(head);

    add_end(&head);
    display_list(head);

    return 0;
}

void
display_list(node *head)
{
    node *cur;

    if (head == NULL) {
        printf("Empty list.\n");
    }

    for (cur = head;  cur != NULL;  cur = cur->next)
        printf("DATA: %d\n", cur->data);
}

void
create_list(node **head, int n)
{
    node *new, *tmp;
    int num, i;

    tmp = *head;

    for (i = 1; i <= n; i++) {
        new = malloc(sizeof(node));
        if (new == NULL) {
            printf("Memory can not be allocated.");
            break;
        }

        printf("Insert element %d: ", i);
        scanf(" %d", &num);

        new->data = num;
        new->next = NULL;

        if (*head == NULL)
            *head = new;
        else
            tmp->next = new;

        tmp = new;
    }
}

// add_begin -- insert at before head of list
void
add_begin(node **head)
{
    node *new;
    int num;

    new = malloc(sizeof(node));
    if (new == NULL) {
        printf("Memory can not be allocated.");
        exit(1);
    }

    printf("Insert element at the beginning: ");
    scanf(" %d", &num);

    new->data = num;
    new->next = *head;

    *head = new;
}

// add_end -- add to tail/end of list
void
add_end(node **head)
{
    node *new;
    node *tmp;
    node *tail;
    int num;

    new = malloc(sizeof(node));
    if (new == NULL) {
        printf("Memory can not be allocated.");
        exit(1);
    }

    printf("Append element at the end: ");
    scanf(" %d", &num);

    new->data = num;
    new->next = NULL;

    // find the tail
    tail = NULL;
    for (tmp = *head;  tmp != NULL;  tmp = tmp->next)
        tail = tmp;

    if (tail != NULL)
        tail->next = new;
    else
        *head = new;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...