c++ - Linked List Not Working Properly -
here code
struct node{ char* isbn; char* author; char* title; char* copyright; char* genre; bool status; node* next; }; struct linkedlist { node* head; // 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 info temp->next = head; head = temp; } void display(){ int = 1; node* = head; while (it != null){ // display book info = 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 @ head.\n"; cout << "2) display books.\n"; cout << "3) exit.\n"; cout << "======================================\n"; cin >> x; switch(x){ case 1:{ cout << "enter isbn: "; cin >> a1; cout << "enter author's name: "; cin >> a2; cout << "enter book title: "; cin >> a3; cout << "enter copyrights: "; cin >> a4; cout << "enter book genre: "; cin >> a5; cout << "enter 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); homecoming 0; } the problem when insert book using case 1 of switch inserts book in linked list given info when come in new book saved book overwritten new book
it's not linked list not working. it's way assign values. givie adress of input buffers (which overwritten @ each reading) , store adress in node.
you have create re-create of buffers (using old c-way strdup()). i'd suggest improve approach: consider utilize of c++ strings.
it's suffichent #include <string> , update struct into:
struct node{ string isbn; string author; string title; string copyright; string genre; bool status; node* next; }; as strings understand correctly assignment char*, wll generate own copy, not realying anymore on buffers. it'll improve though consider replacing char* strings in code.
c++ linked-list
No comments:
Post a Comment