在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);
            } 
        } 
    } 
} 

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)