как реализовать связанный список - PullRequest
0 голосов
/ 16 июня 2020
#include <stdio.h>    
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};

void push(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
new_node->prev = NULL;
if ((*head_ref) != NULL)(*head_ref)->prev = new_node;
(*head_ref) = new_node;}

void append(struct Node** head_ref, int new_data){
    /* 1. allocate node */
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    struct Node* last = *head_ref; /* used in step 5*/
    /* 2. put in the data */
    new_node->data = new_data;
    /* 3. This new node is going to be the last node, so
        make next of it as NULL*/
    new_node->next = NULL;
    /* 4. If the Linked List is empty, then make the new
        node as head */
    if (*head_ref == NULL) {
        new_node->prev = NULL;
        *head_ref = new_node;
        return;}
    /* 5. Else traverse till the last node */
    while (last->next != NULL)
        last = last->next;
    /* 6. Change the next of last node */
    last->next = new_node;
    /* 7. Make last node as previous of new node */
    new_node->prev = last;
    return;}

void insertAfter(struct Node* prev_node, int new_data){
/*1. check if the given prev_node is NULL */
if (prev_node == NULL) {
    printf("the given previous node cannot be NULL");
    return;}
/* 2. allocate new node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
/* 3. put in the data */
new_node->data = new_data;
/* 4. Make next of new node as next of prev_node */
new_node->next = prev_node->next;
/* 5. Make the next of prev_node as new_node */
prev_node->next = new_node;
/* 6. Make prev_node as previous of new_node */
new_node->prev = prev_node;
/* 7. Change previous of new_node's next node */
if (new_node->next != NULL)
    new_node->next->prev = new_node;}

void printList(struct Node* node){
    struct Node* last;
    printf("\nTraversal in forward direction \n");
    while (node != NULL) {
        printf(" %d ", node->data);
        last = node;
        node = node->next;}

    printf("\nTraversal in reverse direction \n");
    while (last != NULL) {
        printf(" %d ", last->data);
        last = last->prev;
    }}


void sortedInsert(struct Node** head, int new_data) {

    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    struct Node* temp;

    if ((*head) == NULL || (new_node->data) > (*head)->prev->data) {
        append(head, new_data);
        return;
    }

    if ((new_node->data) < ((*head)->data)) {
        push(head, new_data);
        return;
    }

    temp = (*head)->next;
    while ((temp->data) < (new_node->data)) {
        temp = temp->next;
    }

    insertAfter(head, new_data);
}
int main() {
struct Node* head = NULL;
sortedInsert(&head, 0);
sortedInsert(&head, 9);
sortedInsert(&head, 4);
sortedInsert(&head, 3);
sortedInsert(&head, 34);
sortedInsert(&head, 15);
printf("\n Created Linked list is: ");
printList(head);
return 0;}

Я пытаюсь написать программу C, в которой данные должны быть вставлены упорядоченным образом (от меньшего к большему). Когда я запускаю код, программа выдает ошибку из-за примечания: ожидается 'struct Node *', но аргумент имеет тип 'struct Node **', как я могу исправить эту проблему, я просмотрел другие решения, такие как: Что означает предупреждение - ожидаемый 'struct node **', но аргумент имеет тип 'struct node ** 'означает? , но они не смогли решить мою проблему. Любая помощь приветствуется

Ответы [ 2 ]

0 голосов
/ 17 июня 2020
    insertAfter(head, new_data);

как я могу исправить эту проблему

Вы забыли разыменовать struct Node** head, как вы правильно делали в других местах функции sortedInsert; чтобы получить правильный тип аргумента, это будет insertAfter(*head, new_data).

Но все равно лог вставки c не совсем правильный; вот исправленная версия:

void sortedInsert(struct Node** head, int new_data) {

    // new node is allocated in append(), push() or insertAfter()
    struct Node* temp;

    if ((*head) == NULL || new_data < (*head)->data) {
        push(head, new_data);
        return;
    }

    temp = *head;
    while (temp->next && temp->next->data < new_data) {
        temp = temp->next;
    }

    insertAfter(temp, new_data);
}
0 голосов
/ 16 июня 2020

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

В качестве примера используйте append(&head, 3) вместо append(head, 3)

...