Добавление узла в начале односвязного списка (C) - PullRequest
3 голосов
/ 02 февраля 2020

Код работает без ошибок, но я не могу понять, почему новый узел не вставляется в начало списка. Возможно, это как-то связано с оператором else в первой функции (insertNode), но я не уверен, что происходит?

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

struct node {
    int data;
    struct node *link;
};

void insertNode(struct node *head, int x) {
    //Create node to be added and add the input integer to it
    struct node *temp;
    temp = (struct node *)malloc(sizeof(struct node));
    temp->data = x;

    //Check if there are any existing nodes in the list, if not, the let the head be equal to the new temp pointer
    if (head == NULL) {
        head = temp;
    } else {
        //If not, then we need to add the node to the beginning
        temp->link = head;
        head = temp;        
        printf("Node was added successfully!\n");
    }
}

int findsize(struct node *head) {
    //Finds the size of the list

    struct node *temp = head;
    int count = 0;
    while (temp != NULL) {
        count++;
        temp = temp->link;
    }
    return count;
}

void printData(struct node *head) {
    //Prints the elements of the list
    struct node *temp = head;
    while (temp != NULL) {
        printf("Element: %d\n", temp->data);
        temp = temp->link;
    }
}

void main() {
    //Created a node and allocated memory
    struct node *head;
    head = (struct node *)malloc(sizeof(struct node));
    //Added data to the node and created another one linked to it
    head->data = 15;
    head->link = (struct node *)malloc(sizeof(struct node));
    head->link->data = 30;
    head->link->link = NULL;
    //Used the above function to add a new node at the beginning of the list
    insertNode(head, 5);
    //Print the size of the list    
    printf("The size of the list you gave is: %d\n", findsize(head));
    //Print the elements of the list
    printData(head);
}

1 Ответ

3 голосов
/ 02 февраля 2020

Когда вы вставляете узел в начало списка, вы фактически изменяете начало списка, поэтому этот новый начальный узел должен быть возвращен вызывающей стороне. Прототип для insertNode() должен быть изменен, чтобы вернуть заголовок списка или взять указатель на заголовок списка.

Вот модифицированная версия с первым подходом:

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

struct node {
    int data;
    struct node *link;
};

struct node *insertNode(struct node *head, int x) {
    //Create node to be added and add the input integer to it
    struct node *temp;
    temp = (struct node *)malloc(sizeof(struct node));
    if (temp != NULL) {
        temp->data = x;
        temp->link = head;
    }
    return temp;
}

int findsize(struct node *head) {
    //Find the size of the list
    struct node *temp = head;
    int count = 0;
    while (temp != NULL) {
        count++;
        temp = temp->link;
    }
    return count;
}

void printData(struct node *head) {
    //Prints the elements of the list
    struct node *temp = head;
    while (temp != NULL) {
        printf("Element: %d\n", temp->data);
        temp = temp->link;
    }
}

void main() {
    //Created a node and allocated memory
    struct node *head = NULL;
    //Insert 3 nodes with values 30, 15 and 5
    head = insertNode(head, 30);
    head = insertNode(head, 15);
    head = insertNode(head, 5);
    //Print the size of the list    
    printf("The size of the list you gave is: %d\n", findsize(head));
    //Print the elements of the list
    printData(head);
    //Should free the nodes
    return 0;
}
...