我不知道如何删除我们在此源代码上添加的最新书籍。我想制作一个堆栈实现程序。因此,如果我们删除一本书,程序将删除最后添加的图书,而不是下面的源代码中添加的第一本书。我对使用指针的堆栈不太了解。谁能修复我的代码?谢谢
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class Book {
int code, year;
string language, name, title;
Book *head, *next, *prev, *link;
public:
Book (string & name, string & title, int code, string & language, int year) {
head = NULL;
this -> name = name;
this -> title = title;
this -> language = language;
this -> code = code;
this -> year = year;
};
~ Book (void) {
delete head;
};
void display (void);
void add (void);
void dellete (void);
};
void Book :: add (void) {
string name, title, language;
int year, code;
system("color E2");
cout << endl << "Author:", cin >> name;
cout << "Title:", cin >> title;
cout << "ISBN code(13 digits):", cin >> code;
cout << "Language:", cin >> language;
cout << "Year of publication:", cin >> year;
Book * p = new Book (name, title, code, language, year);
p -> next = head;
head = p;
}
void Book :: dellete (void) {
string name, title, language;
int year, code;
system("color B0");
Book *p, *prev, *next;
if(head==NULL)
{
cout << "There is no book in the stack\n";
}
else if(head->next==NULL)
{
p = head;
head = NULL;
free(p);
cout << "All book has been deleted. Now the stack is empty\n";
}
else
{
p = head;
while(p->next !=NULL)
{
prev = p;
p = p->next;
}
prev->next = NULL;
free(p);
cout << "A book has been deleted\n";
}
}
void Book :: display (void) {
Book * p = head;
while (p) {
system("color B5");
cout << "----------------------------- \n";
cout << "Author:" << p -> name << endl;
cout << "Title:" << p -> title << endl;
cout << "Number of books" << p -> code << endl;
cout << "Language:" << p -> language << endl;
cout << "Year of publication:" << p -> year << endl;
cout << endl;
p = p -> next;
}
}
int main (int argc, char const ** argv) {
string blank = "";
Book * B = new Book (blank, blank, 0, blank, 0);
int opt;
for (;;) {
system("color A0");
cout << "----------------------------- \n";
cout << "1) Add a book.\n";
cout << "2) Show all books.\n";
cout << "3) Delete a book\n";
cout << "4) Exit. \n";
cout << "Options:", cin >> opt;
switch (opt) {
case 1:
B -> add ();
break;
case 2:
B -> display ();
break;
case 3:
B -> dellete ();
break;
case 4:
exit (0);
default:
continue;
}
}
return 0;
}
我希望有人能帮助我修复此代码。谢谢。
答案 0 :(得分:0)
在删除功能中您不必遍历头指针,下面的代码将解决您遇到的问题
void Book :: dellete (void)
{
string name, title, language;
int year, code;
system("color B0");
Book *p, *prev, *next;
if(head==NULL)
{
cout << "There is no book in the stack\n";
}
else if(head->next==NULL)
{
p = head;
head = NULL;
free(p);
cout << "All book has been deleted. Now the stack is empty\n";
}
else
{
p = head;
head = p->next; // Modified code part
free(p);
cout << "A book has been deleted\n";
}
}
您可能需要清理代码,但首先请查看此更改