双向链表实现图书管理系统
时间: 2023-07-11 19:34:06 浏览: 183
双向链表可以用来实现图书管理系统中的书籍列表。每个节点可以表示一本书,节点中存储该书的相关信息,并且可以通过前后指针实现节点之间的链接。
以下是一个简单的双向链表实现:
```c++
#include <iostream>
#include <string>
using namespace std;
// 书籍信息结构体
struct Book {
string title;
string author;
int year;
};
// 链表节点结构体
struct Node {
Book data;
Node* prev;
Node* next;
};
// 链表类
class BookList {
public:
BookList() : head(nullptr), tail(nullptr), size(0) {}
~BookList() {}
// 添加一本书
void addBook(Book book) {
Node* newNode = new Node();
newNode->data = book;
newNode->prev = tail;
newNode->next = nullptr;
if (tail) {
tail->next = newNode;
}
tail = newNode;
if (!head) {
head = newNode;
}
size++;
}
// 删除一本书
void removeBook(string title) {
Node* curr = head;
while (curr) {
if (curr->data.title == title) {
if (curr->prev) {
curr->prev->next = curr->next;
} else {
head = curr->next;
}
if (curr->next) {
curr->next->prev = curr->prev;
} else {
tail = curr->prev;
}
delete curr;
size--;
return;
}
curr = curr->next;
}
}
// 显示所有书籍
void displayBooks() {
Node* curr = head;
while (curr) {
cout << curr->data.title << " by " << curr->data.author << " (" << curr->data.year << ")" << endl;
curr = curr->next;
}
}
private:
Node* head;
Node* tail;
int size;
};
```
使用示例:
```c++
int main() {
BookList bookList;
bookList.addBook({"The Catcher in the Rye", "J.D. Salinger", 1951});
bookList.addBook({"To Kill a Mockingbird", "Harper Lee", 1960});
bookList.addBook({"1984", "George Orwell", 1949});
bookList.displayBooks();
bookList.removeBook("To Kill a Mockingbird");
bookList.displayBooks();
return 0;
}
```
输出:
```
The Catcher in the Rye by J.D. Salinger (1951)
To Kill a Mockingbird by Harper Lee (1960)
1984 by George Orwell (1949)
The Catcher in the Rye by J.D. Salinger (1951)
1984 by George Orwell (1949)
```
阅读全文