链接列表无法正常工作

时间:2014-06-22 14:49:21

标签: c++ linked-list

这是我的代码

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插入书籍时,它会插入一本书 带有给定数据的链接列表,但是当我输入新书时,先前保存的书籍 被新书覆盖

1 个答案:

答案 0 :(得分:1)

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

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

这对#include <string>来说足够了,并将您的结构更新为:

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

由于字符串正确理解了char *的赋值,它将生成自己的副本,而不是再对你的缓冲区进行重新分析。考虑在所有代码中用字符串替换char *会更好。