Узел вставки связанного списка C в конце - PullRequest
8 голосов
/ 27 апреля 2011

У меня возникли некоторые проблемы с моим методом вставки для связанного списка в C. Кажется, он добавляется только в начале списка.Любая другая вставка, которую я делаю, терпит неудачу.И этот отладчик CodeBlocks так сложно понять, что я до сих пор не понимаю.Это никогда не дает мне ценности, просто адреса в памяти.Во всяком случае, это моя функция.Вы видите какую-либо причину, почему это терпит неудачу?

/* function to add a new node at the end of the list */
int addNodeBottom(int val, node *head){

    //create new node
    node *newNode = (node*)malloc(sizeof(node));

    if(newNode == NULL){
        fprintf(stderr, "Unable to allocate memory for new node\n");
        exit(-1);
    }

    newNode->value = val;

    //check for first insertion
    if(head->next == NULL){
        head->next = newNode;
        printf("added at beginning\n");
    }

    else
    {
        //else loop through the list and find the last
        //node, insert next to it
        node *current = head;
        while(current->next != NULL)
        {
            if(current->next == NULL)
            {
                current->next = newNode;
                printf("added later\n");
            }
            current = current->next;
        }
    }
    return 0;
}

Затем в основном добавляется только 929.

   //testing addNodeBottom function
    addNodeBottom(929, head);
    addNodeBottom(98, head);
    addNodeBottom(122, head);
    addNodeBottom(11, head);
    addNodeBottom(1034, head);

Ответы [ 5 ]

12 голосов
/ 27 апреля 2011

Этот код будет работать.Ответ от samplebias почти правильный, но вам нужно третье изменение:

int addNodeBottom(int val, node *head){

    //create new node
    node *newNode = (node*)malloc(sizeof(node));

    if(newNode == NULL){
        fprintf(stderr, "Unable to allocate memory for new node\n");
        exit(-1);
    }

    newNode->value = val;
    newNode->next = NULL;  // Change 1

    //check for first insertion
    if(head->next == NULL){
        head->next = newNode;
        printf("added at beginning\n");
    }

    else
    {
        //else loop through the list and find the last
        //node, insert next to it
        node *current = head;
        while (true) { // Change 2
            if(current->next == NULL)
            {
                current->next = newNode;
                printf("added later\n");
                break; // Change 3
            }
            current = current->next;
        };
    }
    return 0;
}

Изменение 1: newNode->next должно быть установлено на NULL, поэтому мы не вставляем недопустимые указатели в концеlist.

Change 2/3: цикл заменен на бесконечный цикл, который будет выпадать с break;, когда мы найдем последний элемент.Обратите внимание на то, как while(current->next != NULL) противоречил if(current->next == NULL) раньше.

РЕДАКТИРОВАТЬ: Что касается цикла while, в этом случае это намного лучше:

  node *current = head;
  while (current->next != NULL) {
    current = current->next;
  }
  current->next = newNode;
  printf("added later\n");
2 голосов
/ 27 апреля 2011

После того, как вы malloc a node убедитесь, что установлено node->next = NULL.

int addNodeBottom(int val, node *head)
{    
    node *current = head;
    node *newNode = (node *) malloc(sizeof(node));
    if (newNode == NULL) {
        printf("malloc failed\n");
        exit(-1);
    }    

    newNode->value = val;
    newNode->next = NULL;

    while (current->next) {
        current = current->next;
    }    
    current->next = newNode;
    return 0;
}    

Следует отметить, что в этой версии head по-прежнему используется в качестве фиктивного, а не для хранения значения. Это позволяет вам представлять пустой список, имея только узел head.

0 голосов
/ 12 января 2017

Это прекрасно работает:

struct node *addNode(node *head, int value) {
    node *newNode = (node *) malloc(sizeof(node));
    newNode->value = value;
    newNode->next = NULL;

    if (head == NULL) {
        // Add at the beginning
        head = newNode;
    } else {
        node *current = head;

        while (current->next != NULL) {
            current = current->next;
        };

        // Add at the end
        current->next = newNode;
    }

    return head;
}

Пример использования:

struct node *head = NULL;

for (int currentIndex = 1; currentIndex < 10; currentIndex++) {
    head = addNode(head, currentIndex);
}
0 голосов
/ 12 июня 2016

Новый узел всегда добавляется после последнего узла данного связанного списка.Например, если данный связанный список 5-> 10-> 15-> 20-> 25 и мы добавляем элемент 30 в конце, то связанный список становится 5-> 10-> 15-> 20-> 25-> 30.Поскольку Связанный список обычно представлен его заголовком, мы должны пройти по списку до конца, а затем изменить следующий из последнего узла на новый.

/* Given a reference (pointer to pointer) to the head
   of a list and an int, appends a new node at the end  */


    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 <a href="#">Linked List</a> is empty, then make the new node as head */
        if (*head_ref == 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;
        return;    
}
0 голосов
/ 20 сентября 2013

Я хотел бы упомянуть ключ, прежде чем писать код для вашего рассмотрения.

// Key

temp = адрес нового узла, выделенного функцией malloc (член библиотеки od alloc.h в C)

prev = адрес последнего узла существующего списка ссылок.

next = содержит адрес следующего узла

struct node {
    int data;
    struct node *next;
} *head;

void addnode_end(int a) {
    struct node *temp, *prev;
    temp = (struct node*) malloc(sizeof(node));
    if (temp == NULL) {
        cout << "Not enough memory";
    } else {
        node->data = a;
        node->next = NULL;
        prev = head;

        while (prev->next != NULL) {
            prev = prev->next;
        }

        prev->next = temp;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...