Exception thrown when deleting node from doubly linked list
Mar 17, 2018 at 11:28pm UTC
Hello! I am currently removing similar strings of two doubly linked lists. This function is partly working. It seems to only run into an error when I have to delete two elements in a row. Therefore I think I and not handling the "prev" pointer correctly. If you see anything wrong I would really appreciate the help.
Here is the class header:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#ifndef DBLLINKEDLIST_H
#define DBLLINKEDLIST_H
#include "stdafx.h"
#include <string>
#include "DString.h"
using namespace std;
class Node {
public :
Node() {
next = prev = nullptr ;
}
Node(CDString str) {
data = str;
next = prev = nullptr ;
}
CDString data;
Node *next;
Node *prev;
};
class DblLinkedList {
public :
DblLinkedList();
void push_back(const CDString& str);
void resetIterator() const ;
bool hasMore() const ;
CDString next() const ;
void testConnections();
DblLinkedList(const DblLinkedList& dll);
void operator =(const DblLinkedList& dll);
DblLinkedList::~DblLinkedList();
int getCount();
bool remove(const DblLinkedList & arg);
bool insert(const CDString& str);
friend ostream& operator << (ostream& left, DblLinkedList right);
private :
Node *head, *tail;
mutable Node *it; // mutable says that it can change in a const member function
int count;
};
#endif
Here is the function I am having trouble with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
bool DblLinkedList::remove(const DblLinkedList & arg)
{
CDString strTemp;
DblLinkedList listTemp;
Node *temp;
listTemp = arg;
listTemp.it = listTemp.head;
it = head;
do
{
do
{
if (it == nullptr )
{
it = head;
//it->prev = nullptr;
}
if (it->data == listTemp.it->data)
{
it->prev->next = it->next;
it->next->prev = it->prev;
it = it->next;
if (it->prev == head)
{
head = it;
}
delete it->prev;
count--;
cout << "Removed: " << listTemp.it->data << endl;
}
else
{
it = it->next;
}
} while (!(it == nullptr ));
listTemp.it = listTemp.it->next;
} while (listTemp.it != nullptr ); //removed next
{
cout << "Removal completed\n" ;
return true ;
}
}
I have two successful removes, and then an exception is thrown.
Mar 18, 2018 at 7:02pm UTC
>
mutable Node *it;
¿why is that a member variable?
>
listTemp = arg;
¿deep copy?
1 2 3
it->next->prev = it->prev;
it = it->next;
delete it->prev;
you are not deleting the node that you want, but the previous one (draw a diagram and you'll see it)
you need to make use of functions to simplify your code
1 2 3
for x in this .list:
if other.list.is_member(x):
this .list.erase(x)
Topic archived. No new replies allowed.