【问题标题】:Linked List Not Working Properly链接列表无法正常工作
【发布时间】:2014-06-22 14:49:21
【问题描述】:

这是我的代码

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

问题是,当我使用 switch 的案例 1 插入一本书时,它会插入一本书 具有给定数据的链接列表,但是当我输入新书时,以前保存的书 被新书覆盖了

【问题讨论】:

    标签: c++ linked-list


    【解决方案1】:

    不是链接列表不起作用。这是您分配值的方式。您给它输入缓冲区的地址(在每次读取时都会被覆盖),然后将此地址存储在您的节点中。

    您必须制作缓冲区的副本(使用旧的 C-way strdup())。 我建议一个更好的方法:考虑使用 C++ 字符串。

    #include &lt;string&gt; 就足够了,并将你的结构更新为:

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

    当字符串正确理解来自 char* 的赋值时,它会生成自己的副本,而不是在你的缓冲区上实现。考虑在所有代码中用字符串替换 char* 会更好。

    【讨论】:

      猜你喜欢
      • 2012-12-27
      • 2021-08-10
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2017-04-30
      • 2017-11-28
      相关资源
      最近更新 更多