Добавить элемент в начале связанного списка - PullRequest
0 голосов
/ 23 апреля 2020

Я не понимаю, почему эта функция не добавляет элемент в начало связанного списка. Голова осталась прежней.

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

void beginning(node *head){
     node *new = malloc(sizeof(node));
     int value;
     printf("Insert a number to add at the beginning: ");
     scanf("%d",&value);
     new->data = value;
     new->next = head;
}

Ответы [ 2 ]

1 голос
/ 23 апреля 2020

Вы можете использовать указатель на указатель для решения проблемы. Также вы можете вернуть новое начало с начала ().

node *new_begin(const node *head) {
    node *new = malloc(sizeof(node));
    /* add new node information */
    return new;
}
1 голос
/ 23 апреля 2020

вам нужно изменить

void beginning(node *head){ 

на

void beginning(node **head){

вот мой код:

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


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

typedef struct NODE *Tode;
void create(Tode *head){

     *head = malloc(sizeof(node));
     (*head)->next = NULL;
}
void beginning(Tode *head, int numSize){
    Tode new;
    int value, i;
    for(i = 0; i < numSize; i++){
        new = malloc(sizeof(node));
        scanf("%d",&value);
        new->data = value;
        new->next = (*head)->next;
        (*head)->next = new;
    }
}
void printList(Tode head){
    Tode ptr;
    ptr = head->next;
    printf("\nprint List's value\n");
    while(ptr){
        printf("%d ",ptr->data);
        ptr = ptr->next;
    }
    printf("\n");
}
int main(){
    node *head;
    int numSize;
    create(&head);
    printf("Insert how many  number to add at the beginning: ");
    scanf("%d",&numSize);
    beginning(&head, numSize);
    printList(head);
    // delete(&head);        // youself do
}

результат выполнения:

Insert how many  number to add at the beginning: 5
1 3 6 8 235

print List's value
235 8 6 3 1 
...