如何在已经加载到双链表中的二进制文本中输入和删除节点? C++
我的代码是产品数据库的双链表,我可以选择输入产品、搜索、删除、修改、显示、保存(.bin)和上传(.bin) 在我使用加载二进制选项之前,所有选项都有效。 我的问题是,当我上传包含产品的 .bin 时,输入产品选项不起作用,并且当我想删除列表中的最后一个产品(所有其他选项都有效)时,删除产品不起作用。
这是输入一个产品代码:
void inP() {
product* nuevo = new product();
cout << "Ingrese el nombre del producto: ";
cin >> nuevo->name;
if (first == NULL) {
first = nuevo;
first->next = NULL;
first->previous = NULL;
last = first;
}
else {
last->next = nuevo;
nuevo->next = NULL;
nuevo->previous = last;
last = nuevo;
}
cout << "Producto agregado correctamente a la lista" << endl;
}
这是删除一个产品代码:
void deleteP() {
product* current = new product();
current = first;
product* prev = new product();
prev = NULL;
bool found = false;
string searchP;
cout << "Ingrese el producto a eliminar: ";
cin >> searchP;
if (first != NULL) {
while (current != NULL && found != true) {
if (current->name == searchP) {
cout << "\n Producto ( " << searchP << " ) Encontrado \n" << endl;
cout << "\n" << current->name << " " << current->cant << " " << current->code << " " << current->marca << " " << current->descr << " " << current->monto << "\n";
if (current == first) {
if (first->next == NULL) {
first = NULL;
}
else {
first = first->next;
first->previous = NULL;
}
}
else if (current == last) {
prev->next = NULL;
last = prev;
}
else {
prev->next = current->next;
current->next->previous = prev;
}
cout << "\n Producto Eliminado" << endl;
found = true;
}
prev = current;
current = current->next;
}
if (!found) {
cout << "\n Producto no encontrado \n" << endl;
}
}
else {
cout << "\n La lista de productos esta vacia \n" << endl;
}
}
这是加载二进制代码:
void loadBin() {
ifstream is(registryName, ios::in | ios::binary);
product* reader;
if (is.is_open()) {
is.seekg(0, ios::end);
int size = is.tellg();
is.seekg(0, ios::beg);
while (is.tellg() < size) {
reader = new product;
is.read((char*)reader, sizeof(product));
reader->next = NULL;
cout << reader->name << endl;
if (first == NULL) {
first = reader;
}
else {
product* indice = first;
while (indice->next != NULL) {
indice = indice->next;
}
indice->next = reader;
}
}
is.close();
}
}
以及所有代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string registryName = "products.bin";
struct product {
string name;
product* next;
product* previous;
}*first, * last;
void inP();
void outP();
void searchP();
void modifyP();
void deleteP();
void saveBin();
void loadBin();
int main() {
int op;
do {
system("CLS");
cout << "Menu:" << endl;
cout << "1. Input a Product " << endl;
cout << "2. Show the list " << endl;
cout << "3. Search a Product " << endl;
cout << "4. Modify a product " << endl;
cout << "5. Delete a product " << endl;
cout << "6. Save List " << endl;
cout << "7. Load Binary List " << endl;
cout << "8. Exit" << endl;
cin >> op;
cout << "\n";
switch (op) {
case 1: {
inP();
cout << "\n";
system("PAUSE");
break;
}
case 2: {
outP();
system("PAUSE");
break;
}
case 3: {
searchP();
system("PAUSE");
break;
}
case 4: {
modifyP();
system("PAUSE");
break;
}
case 5:
{
deleteP();
system("PAUSE");
break;
}
case 6: {
saveBin();
break;
}
case 7: {
loadBin();
break;
}
case 8: {
return 0;
}
default: cout << "No ingreso una opcion disponible" << endl;
break;
}
} while (op!=8);
return 0;
}
void inP() {
product* nuevo = new product();
cout << "Ingrese el nombre del producto: ";
cin >> nuevo->name;
if (first == NULL) {
first = nuevo;
first->next = NULL;
first->previous = NULL;
last = first;
}
else {
last->next = nuevo;
nuevo->next = NULL;
nuevo->previous = last;
last = nuevo;
}
cout << "Producto agregado correctamente a la lista" << endl;
}
void outP() {
product* current = new product();
current = first;
if (first != NULL) {
while (current != NULL) {
cout << "\n" << current->name;
current = current->next;
}
}
else {
cout << "No hay productos en la lista" << endl;
cout << "\n";
}
cout << "\n" << endl;
}
void searchP() {
product* current = new product();
current = first;
bool found = false;
string searchP;
cout << "Ingrese el producto a buscar: ";
cin >> searchP;
if (first != NULL) {
while (current != NULL && found != true) {
if (current->name == searchP) {
cout << "\n Producto ( " << searchP << " ) Encontrado \n" << endl;
found = true;
}
current = current->next;
}
if (!found) {
cout << "\n Producto no encontrado \n" << endl;
}
}
else {
cout << "\n La lista de productos esta vacia \n" << endl;
}
}
void modifyP() {
product* current = new product();
current = first;
bool found = false;
string searchP;
cout << "Ingrese el producto a modificar: ";
cin >> searchP;
if (first != NULL) {
while (current != NULL && found != true) {
if (current->name == searchP) {
cout << "\n Producto ( " << searchP << " ) Encontrado \n" << endl;
cout << "\n Ingrese el nuevo nombre del Producto: ";
cin >> current->name;
cout << "\n Producto Modificado Correctamente \n" << endl;
found = true;
}
current = current->next;
}
if (!found) {
cout << "\n Producto no encontrado \n" << endl;
}
}
else {
cout << "\n La lista de productos esta vacia \n" << endl;
}
}
void deleteP() {
product* current = new product();
current = first;
product* prev = new product();
prev = NULL;
bool found = false;
string searchP;
cout << "Ingrese el producto a eliminar: ";
cin >> searchP;
if (first != NULL) {
while (current != NULL && found != true) {
if (current->name == searchP) {
cout << "\n Producto ( " << searchP << " ) Encontrado \n" << endl;
if (current == first) {
if (first->next == NULL) {
first = NULL;
}
else {
first = first->next;
first->previous = NULL;
}
}
else if (current == last) {
prev->next = NULL;
last = prev;
}
else {
prev->next = current->next;
current->next->previous = prev;
}
cout << "\n Producto Eliminado" << endl;
found = true;
}
prev = current;
current = current->next;
}
if (!found) {
cout << "\n Producto no encontrado \n" << endl;
}
}
else {
cout << "\n La lista de productos esta vacia \n" << endl;
}
}
void saveBin() {
ofstream os(registryName, ios::out | ios::binary);
if (os.is_open()) {
product* indice = first;
while (indice != NULL) {
os.write((char*)indice, sizeof(product));
indice = indice->next;
}
os.close();
}
}
void loadBin() {
ifstream is(registryName, ios::in | ios::binary);
product* reader;
if (is.is_open()) {
is.seekg(0, ios::end);
int size = is.tellg();
is.seekg(0, ios::beg);
while (is.tellg() < size) {
reader = new product;
is.read((char*)reader, sizeof(product));
reader->next = NULL;
cout << reader->name << endl;
if (first == NULL) {
first = reader;
}
else {
product* indice = first;
while (indice->next != NULL) {
indice = indice->next;
}
indice->next = reader;
}
}
is.close();
}
}
My code its a double linked list of a products database, i have the options to input a product, search, delete, modify, show, save (.bin) and upload(.bin)
All the options works before i use the load binary option.
My problem is that when i upload the .bin with products the input a product option doesn´t and the delete a product does not work when i want to delete the last product in the list (all the others options works).
This is the input a product code:
void inP() {
product* nuevo = new product();
cout << "Ingrese el nombre del producto: ";
cin >> nuevo->name;
if (first == NULL) {
first = nuevo;
first->next = NULL;
first->previous = NULL;
last = first;
}
else {
last->next = nuevo;
nuevo->next = NULL;
nuevo->previous = last;
last = nuevo;
}
cout << "Producto agregado correctamente a la lista" << endl;
}
This is the delete a product code:
void deleteP() {
product* current = new product();
current = first;
product* prev = new product();
prev = NULL;
bool found = false;
string searchP;
cout << "Ingrese el producto a eliminar: ";
cin >> searchP;
if (first != NULL) {
while (current != NULL && found != true) {
if (current->name == searchP) {
cout << "\n Producto ( " << searchP << " ) Encontrado \n" << endl;
cout << "\n" << current->name << " " << current->cant << " " << current->code << " " << current->marca << " " << current->descr << " " << current->monto << "\n";
if (current == first) {
if (first->next == NULL) {
first = NULL;
}
else {
first = first->next;
first->previous = NULL;
}
}
else if (current == last) {
prev->next = NULL;
last = prev;
}
else {
prev->next = current->next;
current->next->previous = prev;
}
cout << "\n Producto Eliminado" << endl;
found = true;
}
prev = current;
current = current->next;
}
if (!found) {
cout << "\n Producto no encontrado \n" << endl;
}
}
else {
cout << "\n La lista de productos esta vacia \n" << endl;
}
}
This is the load binary code:
void loadBin() {
ifstream is(registryName, ios::in | ios::binary);
product* reader;
if (is.is_open()) {
is.seekg(0, ios::end);
int size = is.tellg();
is.seekg(0, ios::beg);
while (is.tellg() < size) {
reader = new product;
is.read((char*)reader, sizeof(product));
reader->next = NULL;
cout << reader->name << endl;
if (first == NULL) {
first = reader;
}
else {
product* indice = first;
while (indice->next != NULL) {
indice = indice->next;
}
indice->next = reader;
}
}
is.close();
}
}
And all the code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string registryName = "products.bin";
struct product {
string name;
product* next;
product* previous;
}*first, * last;
void inP();
void outP();
void searchP();
void modifyP();
void deleteP();
void saveBin();
void loadBin();
int main() {
int op;
do {
system("CLS");
cout << "Menu:" << endl;
cout << "1. Input a Product " << endl;
cout << "2. Show the list " << endl;
cout << "3. Search a Product " << endl;
cout << "4. Modify a product " << endl;
cout << "5. Delete a product " << endl;
cout << "6. Save List " << endl;
cout << "7. Load Binary List " << endl;
cout << "8. Exit" << endl;
cin >> op;
cout << "\n";
switch (op) {
case 1: {
inP();
cout << "\n";
system("PAUSE");
break;
}
case 2: {
outP();
system("PAUSE");
break;
}
case 3: {
searchP();
system("PAUSE");
break;
}
case 4: {
modifyP();
system("PAUSE");
break;
}
case 5:
{
deleteP();
system("PAUSE");
break;
}
case 6: {
saveBin();
break;
}
case 7: {
loadBin();
break;
}
case 8: {
return 0;
}
default: cout << "No ingreso una opcion disponible" << endl;
break;
}
} while (op!=8);
return 0;
}
void inP() {
product* nuevo = new product();
cout << "Ingrese el nombre del producto: ";
cin >> nuevo->name;
if (first == NULL) {
first = nuevo;
first->next = NULL;
first->previous = NULL;
last = first;
}
else {
last->next = nuevo;
nuevo->next = NULL;
nuevo->previous = last;
last = nuevo;
}
cout << "Producto agregado correctamente a la lista" << endl;
}
void outP() {
product* current = new product();
current = first;
if (first != NULL) {
while (current != NULL) {
cout << "\n" << current->name;
current = current->next;
}
}
else {
cout << "No hay productos en la lista" << endl;
cout << "\n";
}
cout << "\n" << endl;
}
void searchP() {
product* current = new product();
current = first;
bool found = false;
string searchP;
cout << "Ingrese el producto a buscar: ";
cin >> searchP;
if (first != NULL) {
while (current != NULL && found != true) {
if (current->name == searchP) {
cout << "\n Producto ( " << searchP << " ) Encontrado \n" << endl;
found = true;
}
current = current->next;
}
if (!found) {
cout << "\n Producto no encontrado \n" << endl;
}
}
else {
cout << "\n La lista de productos esta vacia \n" << endl;
}
}
void modifyP() {
product* current = new product();
current = first;
bool found = false;
string searchP;
cout << "Ingrese el producto a modificar: ";
cin >> searchP;
if (first != NULL) {
while (current != NULL && found != true) {
if (current->name == searchP) {
cout << "\n Producto ( " << searchP << " ) Encontrado \n" << endl;
cout << "\n Ingrese el nuevo nombre del Producto: ";
cin >> current->name;
cout << "\n Producto Modificado Correctamente \n" << endl;
found = true;
}
current = current->next;
}
if (!found) {
cout << "\n Producto no encontrado \n" << endl;
}
}
else {
cout << "\n La lista de productos esta vacia \n" << endl;
}
}
void deleteP() {
product* current = new product();
current = first;
product* prev = new product();
prev = NULL;
bool found = false;
string searchP;
cout << "Ingrese el producto a eliminar: ";
cin >> searchP;
if (first != NULL) {
while (current != NULL && found != true) {
if (current->name == searchP) {
cout << "\n Producto ( " << searchP << " ) Encontrado \n" << endl;
if (current == first) {
if (first->next == NULL) {
first = NULL;
}
else {
first = first->next;
first->previous = NULL;
}
}
else if (current == last) {
prev->next = NULL;
last = prev;
}
else {
prev->next = current->next;
current->next->previous = prev;
}
cout << "\n Producto Eliminado" << endl;
found = true;
}
prev = current;
current = current->next;
}
if (!found) {
cout << "\n Producto no encontrado \n" << endl;
}
}
else {
cout << "\n La lista de productos esta vacia \n" << endl;
}
}
void saveBin() {
ofstream os(registryName, ios::out | ios::binary);
if (os.is_open()) {
product* indice = first;
while (indice != NULL) {
os.write((char*)indice, sizeof(product));
indice = indice->next;
}
os.close();
}
}
void loadBin() {
ifstream is(registryName, ios::in | ios::binary);
product* reader;
if (is.is_open()) {
is.seekg(0, ios::end);
int size = is.tellg();
is.seekg(0, ios::beg);
while (is.tellg() < size) {
reader = new product;
is.read((char*)reader, sizeof(product));
reader->next = NULL;
cout << reader->name << endl;
if (first == NULL) {
first = reader;
}
else {
product* indice = first;
while (indice->next != NULL) {
indice = indice->next;
}
indice->next = reader;
}
}
is.close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很多很多问题和误解。 。 。
首先。我在代码中的任何地方都看不到链接列表。没有任何地方有带有列表的语句或变量。
相反,您有一个名为“product”的
Node
和 2 个指向该数据类型的全局指针。然后,您手动将Node
实例链接在一起并相应地更新全局指针。没有“职责分离”,而且有很多重复。
正常的方法是创建一个
class
或struct
DoublyLinkedList,其中包含节点以及第一个和最后一个指针。然后这个class
或struct
将提供您需要的所有接口函数,并从oudsite世界隐藏所有内部实现。然后,进行存储和保存。当然,您永远不会存储节点“products”的指针,也不能将
std::string
存储为二进制文件。std::string
是一种复杂的数据类型,具有一些对您不可见的内部状态。这是行不通的。相反,您需要对数据进行序列化/反序列化。这意味着您只需将重要数据存储为可读文本即可。
标准方法是覆盖自定义数据类型(此处为“产品”)的插入运算符
<<
和提取运算符>>
。这可以通过简单地添加这些语句(放入您的 struct 定义中)来完成
,这些语句将覆盖
<<
和>>
运算符为您的结构
。在函数中,我们只需将“名称”写入流或从流中读取“名称”即可。定义这些覆盖后,我们可以编写:
编译器将识别与
>>
或<<
运算符一起使用的数据类型“product”并调用函数在您的struct
中定义。另外:您对 new 和指针有一些误解。即使不需要,您也总是会创建新的
产品
。例如,在“deleteP”函数中,您编写“
为什么要创建新的“产品”?你只需要定义一个指针。
因此,必须改用以下方法:
这将导致我们遇到代码中的下一个也是最严重的问题。您没有释放使用函数
new
分配的内存。new
将通过操作系统/标准库分配/获取内存。并且您分配的所有内存都必须稍后使用delete
函数再次释放。由于您没有删除任何内容,因此您正在造成内存泄漏。
所有
新建
的内容都必须删除
。基本上,C++ 中不应该使用自有内存的 new、delete 和原始指针。
但是,一步接着一步。首先,我们用最少的必要修正来修复代码(仍然存在内存泄漏)。但添加反/序列化。
这段代码仍然存在很多问题。最大的问题是内存泄漏。而且,还有一个。您没有“clearP”功能,该功能将删除所有节点。这样的“clearP”函数通常必须在任何“loadBin”函数之前调用。否则,如果已经有可用元素,“loadBin”将从磁盘中附加数据到节点末尾。
所以,我们需要添加一个“clearP”函数。在下一步重构中,我们还将释放分配的内存。我们将在“deleteP”函数中执行此操作,并在
main
末尾和“loadBin”函数中调用“clearP”。通过此更正,我们将得到:
仍然不是真正的链接列表,但已经可以工作。
不幸的是,我无法向您展示真实列表的一些示例实现,因为 SO 将答案的长度限制为 30000 。 。 。
Many many problems and misunderstandings . . .
First of all. I cannot see a linked list anywhere in your code. There is nowhere a statement or a variable with a list.
Instead, you have a
Node
called "product" and 2 global pointers to this data type. Then you manually link theNode
instances together and update the global pointers correspondingly.There is no "Segregation of Duties" and there are a lot of repetitions.
The normal approach would be to create a
class
orstruct
DoublyLinkedList, which would contain nodes and the first and last pointers. Then thisclass
orstruct
would provide all interface functions that you need and hide all implementation internas from the oudsite world.Then, for storing and saving. You would of course never store the pointers of the node "products" and cannot store a
std::string
as a binary.std::string
is a complex data type with some internal state invisible for you. This does not work.Instead you need to do a serialization / deserialization of your data. This means that you just store the important data as a readable text.
The standard approach is to overwrite the insertion operator
<<
and the extraction operator>>
for your custom data type, here "product".This can be done by simply adding
These statements (put into your
struct
definition) will overwrite the<<
and>>
operator for yourstruct
. Within the function, we simply write the "name" to the stream or read the "name" from the stream.After having defined those overrides, we could write:
The compiler will recognize data type "product" used with the
>>
or<<
operator and call the functions defined in yourstruct
.Additionally: You have some misunderstandings about new and pointers. You always create new
products
, even, if not needed.For example in your "deleteP" function you write
Why do you create a new "product"? You just need to define a pointer.
So, the following approach must be used instead:
And this leads us to the next and most severe problem in your code. You are not releasing the memory that you allocate with the function
new
.new
will allocate/get memory via the operating system/stdandard-library. And all memory that you allocate, must be released again later with thedelete
function.And since you do not delete anything, you are creating memory leaks like hell.
Everthing that is
new
ed, must bedelete
d.And basically
new
,delete
and raw pointers for owned memory should not be used in C++.But, one step after the other. First we fix the code with the minimum necessary correction (still with memory leaks). But adding de/serialization.
This code still has many problems. The biggest ones are the memory leaks. And, an additional one. You have no "clearP" function, which will remove all nodes. Such a "clearP" function must normally be called before any "loadBin" function. Otherwise, id there are already elements available, "loadBin" will append data from the disk at the end of the nodes.
So, we need to add a "clearP" function. And in the next refactoring step, we will also release also the allocated memory. This we will do in the "deleteP" function and by calling "clearP" at the end of
main
and in the "loadBin" function.With this corrections we will get:
Still not a real llinked list, but already working.
Unfortunately I cannot show you the some example implementations for real lists, because SO limits answers to a lengt of 30000 . . .