Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone show me how to complete the copy constructor, assignment operator, a

ID: 3673447 • Letter: C

Question

Can someone show me how to complete the copy constructor, assignment operator, and output operator in the following c++ header file?

#include <cstdlib>

#include <iostream>

using namespace std;

class DoublyLinkedList; // class declaration

// list node

class DListNode {

private: int obj;

DListNode *prev, *next;

friend class DoublyLinkedList;

public:

DListNode(int e=0, DListNode *p = NULL, DListNode *n = NULL)

: obj(e), prev(p), next(n) {}

int getElem() const { return obj; }

DListNode * getNext() const { return next; }

DListNode * getPrev() const { return prev; }

};

// doubly linked list

class DoublyLinkedList {

protected: DListNode header, trailer;

public:

DoublyLinkedList() : header(0), trailer(0) // constructor

{ header.next = &trailer; trailer.prev = &header; }

DoublyLinkedList(const DoublyLinkedList& dll); // copy constructor

~DoublyLinkedList(); // destructor

DoublyLinkedList& operator=(const DoublyLinkedList& dll); // assignment operator

// return the pointer to the first node

DListNode *getFirst() const { return header.next; }

// return the pointer to the trailer

const DListNode *getAfterLast() const { return &trailer; }

// return if the list is empty

bool isEmpty() const { return header.next == &trailer; }

int first() const; // return the first object

int last() const; // return the last object

void insertFirst(int newobj); // insert to the first of the list

int removeFirst(); // remove the first node

void insertLast(int newobj); // insert to the last of the list

int removeLast(); // remove the last node

};

// output operator

ostream& operator<<(ostream& out, const DoublyLinkedList& dll);

Explanation / Answer

Answer:

// copy constructor

template <class T> DoublyLinkedList<T>::DoublyLinkedList(DoublyLinkedList<T>& dll)
{
  
header.next = &trailer;
trailer.prev = &header;
if (!dll.isEmpty())
{
DListNode<T>* element;
element=dll.getFirst();
while (element!=dll.getAfterLast())
{
insertLast(element->getElem());
element=element->getNext();
}
}
}
// assignment operator
template <class T> DoublyLinkedList<T>& DoublyLinkedList<T>::operator=(DoublyLinkedList<T>& dll)
{

DListNode<T> *prev_node, *element = header.next;
while (element!= &trailer)
{
prev_node = element;
element = element->next;
delete prev_node;
}
header.next = &trailer;
trailer.prev = &header;
  
if (!dll.isEmpty())
{
element=dll.getFirst();
while (element!=dll.getAfterLast())
{
insertLast(element->getElem());
element=element->getNext();
}
}
  
}
// output operator
template <class T> ostream& operator<<(ostream& out, DoublyLinkedList<T>& dll)
{
DListNode<T>* read=dll.getFirst();
while (read!=dll.getAfterLast())
{ T object=read->getElem();
out<<object<<endl;
read=read->getNext();
}
return out;
}