链表不能正常工作

Linked List Not Working Properly

本文关键字:工作 常工作 不能 链表      更新时间:2023-10-16

这是我的代码

struct Node{
    char* isbn;
    char* author;
    char* title;
    char* copyright;
    char* genre;
    bool status;
    Node* next;
};
struct LinkedList {
Node* head; // This is the starting pointer of Linked List
LinkedList(){
    head = NULL;
}
void insertAtHead(char* a, char* b, char* c, char* d, char* e, bool f){
    Node* temp = new Node;
    temp->isbn = a;
    // etc. assigning information
    temp->next = head;
    head = temp;
}
void display(){
    int i = 1;
    Node* it = head;
    while (it != NULL){
        // display book info
        it = it->next;
        i++;
    }
    cout << "n";
}
};
int main(){
    LinkedList LL;
    int x;
    char a1[10] = "";
    char a2[25] = "";
    char a3[25] = "";
    char a4[15] = "";
    char a5[15] = "";
    bool a6 = 0;
do{
    cout << "n======================================n";
    cout << "1) Insert Book At Head.n";
    cout << "2) Display All Books.n";
    cout << "3) Exit.n";
    cout << "======================================n";
    cin >> x;
switch(x){
case 1:{
    cout << "Enter ISBN: "; cin >> a1;
    cout << "Enter The Author's Name: "; cin >> a2;
    cout << "Enter The Book Title: "; cin >> a3;
    cout << "Enter The CopyRights: "; cin >> a4;
    cout << "Enter The Book Genre: "; cin >> a5;
    cout << "Enter The Status Of Book: "; cin >> a6;
    LL.insertAtHead(a1,a2,a3,a4,a5,a6);
    break;
    }
case 2:
    LL.display();
    break;
case 3:
    break;
}
}while(x!=3);
    return 0;
}

问题是,当我插入一本书使用情况1的开关,它插入一本书在链表与给定的数据,但当我输入一个新的书,以前保存的书被新书覆盖

不是链表不起作用。这是你赋值的方式。您给它输入缓冲区的地址(每次读取时覆盖),并将此地址存储在节点中。

你必须复制你的缓冲区(使用旧的c方式strdup())。我建议一个更好的方法:考虑使用c++字符串。

这是足够的#include <string>和更新你的结构为:

struct Node{
    string isbn;
    string author;
    string title;
    string copyright;
    string genre;
    bool status;
    Node* next;
};

由于字符串可以正确地理解char*的赋值,它将生成自己的副本,而不再占用缓冲区。考虑将所有代码中的char*替换为字符串会更好。