首页 > 解决方案 > 在 C++ 中的有序链表中插入一个新节点

问题描述

我正在使用 c++ 在 Visual Studio 中编写一些代码,它是一个有序链表,但我在使用指针时遇到了一些麻烦。

我有三种不同的方法/功能来执行这项任务。

/*
 * insert_head: Insert a node at the beginning of the list.
*/
book *inserta_head(book *head, book *newNode){
    newNode->next = head; 
    return newNode;
} 

/*
 * insert_after: Insert a new node after another one.
*/
void insert_after(book *node, book *newNode){
    newNode->next = node->next;
    node->next = newNode;
} 

/*
 * insert: Adds a new node (ordered by code) to the list.         
*/
void insert(book* head, int code, char name[40], char lastName[40], char title[40], int year, int lend) {
    book* newNode = crear_libro(code, name, lastName, title, year, lend);
    book* aux = head;

    // If the list is empty.
    if (head == NULL){
       head = insert_head(head, newNode); 
    } else {
        // If the new node goes before the head.
        if (aux->code > newNode->code){
            head = insert_head(head,newNode);
        } else { 
            while (aux != nullptr && aux->code < newNode->code)
                aux = aux->next;
            // Verify the code isn't repeated
            if (aux != nullptr && aux->code == newNode->code){
                printf("Error: Verify the code. \n");
            } else {
                insert_after(aux,newNode);
            } 
        } 
    } 
} 

我试过运行代码。每次我尝试打印列表时,它都会说它是空的。我检查了我的打印方法和创建节点的方法,它们都在工作,所以我很确定它与指针有关,但我找不到错误。

标签: c++linked-list

解决方案


您的insert函数会更改head指针。但是该指针是您调用该函数的头指针的副本。所以insert函数外的头指针是不变的。这就是为什么没有任何东西被添加到列表中。

一个简单的解决方法是使head参数成为参考。

void insert(book*& head, int code, ...

推荐阅读