Question: The functions work but they are not passing edge cases. The remove after function needs to throw an exception when the they try to remove
The functions work but they are not passing edge cases. The remove after function needs to throw an exception when the they try to remove the trailer node. The remove before function needs to throw an exception when they try to remove the header node. This is a double linked list class using a struct for the node, A snipped of the header can be seen below. My move constructor needs to handle trying to move an empty list.
struct DLListNode {
int obj;
DLListNode *prev, *next;
// constructor
DLListNode(int e=0, DLListNode *p=nullptr, DLListNode *n=nullptr): obj(e), prev(p), next(n){}
};
// doubly linked list class
class DLList {
private:
DLListNode header, trailer;
public:
DLList::DLList() : header(0), trailer(0)
{
//set next and prev to values of trailer and header
header.next = &trailer;
trailer.prev = &header;
}
DLList(const DLList& dll); // copy constructor
DLList(DLList&& dll); // move constructor
~DLList(); // destructor
....
---------------------------------------
DLList::DLList(DLList &&dll)// move constructor
{
// moving values without copying
if (!this->is_empty())
{
header.next = dll.header.next;
trailer.prev = dll.trailer.prev;
dll.header.next->prev = &header;
trailer.prev->next = &trailer;
dll.header.next = &dll.trailer;
dll.trailer.prev = &dll.header;
}
else
{
header.next = &trailer;
trailer.prev = &header;
}
}
int DLList::remove_after(DLListNode &p)
{
if (this->is_empty())
throw("Empty List");
if (&p == &trailer)
{
throw("Error: reached the end of list");
}
DLListNode *temp = p.next;
temp->next->prev = &p;
p.next = temp->next;
int nodes_obj = temp->obj;
delete temp;
return nodes_obj;
}
int DLList::remove_before(DLListNode &p)
{
if (this->is_empty())
{
throw("Empty List");
}
else
{
DLListNode *temp = p.prev;
temp->prev->next = &p;
p.prev = temp->prev;
int nodes_obj = temp->obj;
delete temp;
return nodes_obj;
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
