SinglyLinkedList implementation with rule of 3 - c++

I'm new to C++ and have been trying to implement a Singly Linked List, that provides an implementation the destructor, copy constructor and assignment operator. I'm running into compilation issues when trying to implement the copy constructor and the assignment operator.
Here's node.hpp
#ifndef LINKED_LIST_NODE_HPP
#define LINKED_LIST_NODE_HPP
template <typename T>
class Node{
public:
T data;
Node* next;
Node();
Node(T);
Node(const Node&);
~Node();
};
template <typename T>
Node<T>::Node(){}
template <typename T>
Node<T>:: Node(const T data): data(data), next(nullptr){}
template <typename T>
Node<T>::Node(const Node<T>& source) : data(source.data),
next(new Node)
{
(*next) = *(source.next) ;
}
template <typename T>
Node<T>::~Node(){}
#endif //LINKED_LIST_NODE_HPP
This is singly_linked_list.hpp
#ifndef LINKED_LIST_SINGLYLINKEDLIST_HPP
#define LINKED_LIST_SINGLYLINKEDLIST_HPP
#include <iostream>
#include "node.hpp"
template <typename T>
class SinglyLinkedList {
private:
Node<T>* head;
std::size_t count;
public:
SinglyLinkedList();
SinglyLinkedList(const SinglyLinkedList& source);
SinglyLinkedList& operator=(const SinglyLinkedList& source);
~SinglyLinkedList();
void insert(T);
void remove(T);
bool isEmpty();
int length();
void print();
};
template <typename T>
SinglyLinkedList<T>::SinglyLinkedList() : head(nullptr), count(0){}
template <typename T>
template <typename T>
SinglyLinkedList<T>::SinglyLinkedList(const SinglyLinkedList& source){
Node<T>* curr = source.head;
while(curr != nullptr){
Node<T>* p = new Node<T>;
p->data = curr->data;
curr = curr->next;
}
}
//template <typename T>
//SinglyLinkedList<T>::SinglyLinkedList& operator=(const SinglyLinkedList<T>& source){
// //not sure how to implment this.
//}
template <typename T>
SinglyLinkedList<T>::~SinglyLinkedList() {
if(!isEmpty()){
Node<T>* temp = head;
Node<T>* prev = nullptr;
while(temp->next != nullptr){
prev = temp;
temp = temp->next;
delete prev;
}
delete temp;
}
}
template <typename T>
bool SinglyLinkedList<T>::isEmpty() {
return head == nullptr;
}
template <typename T>
void SinglyLinkedList<T>::insert(T item) {
Node<T>* p = new Node<T>(item);
p->next = head;
head = p;
count += 1;
}
template <typename T>
void SinglyLinkedList<T>::remove(T item) {
bool present = false;
if (head->data == item){
Node<T>* temp = head;
head = head->next;
delete(temp);
count -= 1;
return;
}
Node<T>* temp = head;
while (temp->next != nullptr){
if (temp->next->data == item){
Node<T>* removable = temp->next;
temp->next = temp->next->next;
delete(removable);
present = true;
count -= 1;
break;
} else{
temp = temp->next;
}
}
if(!present){
throw std::invalid_argument("item not present in list");
}
}
template <typename T>
int SinglyLinkedList<T>::length() {
return count;
}
template <typename T>
void SinglyLinkedList<T>::print() {
if(isEmpty()){
throw std::invalid_argument("Can't print an empty list!");
}
Node<T>* temp = head;
while(temp != nullptr){
if(temp->next != nullptr){
std::cout<<temp->data;
std::cout<<"->";
}else{
std::cout<<temp->data;
}
temp = temp->next;
}
std::cout<<std::endl;
}
#endif //LINKED_LIST_SINGLYLINKEDLIST_HPP
I've commented out the copy constructor code to make this compile. What is the correct way of doing this? I'm just learning C++.

One issue that introduces complexity is that it is not well defined what the copy constructor of a node should do? Should the next field of the copy point to the next of the original, or it should create a copy of the next and point to that? The former is inadequate and error-prone, the latter would recursively create a copy of the whole list, one node at a time. This will work for lists of small size but will cause stack overflow for lists with many elements due to the depth of the recursive calls.
So to keep things simple, I wouldn't bother with copy constructor of a node.
template <typename T>
class Node {
public:
T data;
Node* next = nullptr;
Node() = default;
Node(const Node&) = delete; // since copying is not well defined, make it impossible to copy a node.
};
Copying a list is a well defined operation, so implementing the copy constructor makes sense. A mistake with your current implementation is that you allocate a new node, only to leak it later (nothing keeps track of the newly allocated node p). What you need looks more like this:
template <typename T>
SinglyLinkedList<T>::SinglyLinkedList(const SinglyLinkedList<T>& source)
: head(nullptr)
, count(0)
{
// deal with the trivial case of empty list
if (source.head == nullptr)
return;
// deal with the case where count >= 1
head = new Node<T>;
head->data = source.head->data;
head->next = nullptr;
count = 1;
Node<T>* lastCopied = source.head; // last node to be copied
Node<T>* lastAdded = head; // last node to be added to the current list
while (lastCopied->next != nullptr)
{
// create new node
Node<T>* p = new Node<T>;
p->data = lastCopied->next->data;
p->next = nullptr;
// link the newly created node to the last of the current list
lastAdded->next = p;
lastAdded = p;
// advance lastCopied
lastCopied = lastCopied->next;
count++;
}
}
Now regarding the assignment operator, luckily you can use the 'copy and swap' idiom that greatly simplifies things.
template <typename T>
SinglyLinkedList<T>& SinglyLinkedList<T>::operator =(SinglyLinkedList<T> source) // note that you pass by value.
{
std::swap(head, source.head);
std::swap(count, source.count);
return *this;
}
My answer would become too long if I tried to explain the copy and swap technique. It is a clever trick to write exception safe code and avoid duplication (implements assignment by using the copy ctor) at the same time. It is worth reading about it here.
Btw, the declaration of your class should look like this
template <typename T>
class SinglyLinkedList
{
private:
Node<T>* head = nullptr;
std::size_t count = 0;
public:
SinglyLinkedList(const SinglyLinkedList& source);
SinglyLinkedList& operator=(SinglyLinkedList source);
// other members here...
};
PS. My code assumes you are using c++11 or a later standard.

I don't like the direction this is headed. I'm going to explain how to do this approach right because it is an excellent lesson on recursion, but because it's recursion it can run the program out of Automatic storage (march off the end of the stack, most likely) with a sufficiently large list. Not cool.
The logic:
Copying a node copies the next node if there is one. This looks something like
template <typename T>
Node<T>::Node(const Node<T>& source) : data(source.data)
{
if (source.next) // if there is a next, clone it
{
next = new Node<T>(*source.next);
}
else
{
next = nullptr;
}
}
This reduces the linked list copy constructor to
template <typename T>
SinglyLinkedList<T>::SinglyLinkedList(const SinglyLinkedList& source){
head = new Node<T>(*source.head); //clone the head. Cloning the head will clone everything after
count = source.count;
}
A helper function may, uh... help here to make the Node copy constructor a bit more idiomatic
template <typename T>
Node<T> * initnext(const Node<T> & source)
{
if (source.next)
{
return new Node<T>(*source.next);
}
else
{
return nullptr;
}
}
template <typename T>
Node<T>::Node(const Node<T>& source) : data(source.data),
next(initnext(source))
{
}
but I don't think you gain much.
So... I don't like the above. What would I do instead? Something a lot like opetroch's solution above, but different enough that I'll write this up.
The node stays brutally stupid. As far as I'm concerned all a Node should ever know is how to store the payload and find other Nodes. This means the linked list should do all of the heavy lifting.
Concept 1: head is nothing but a next pointer. Once you abstract away its differences, unimportant here, you can use it exactly the same way you would next.
Concept 2: If you only know where next points, you have to do a bunch of extra book-keeping to track the previous node to update it's next. But if you take advantage of the previous's next pointing to the current node, you can throw out even more code. By tracking the previous node's next you have all of the information you need.
Concept 3: If you keep a pointer to the previous node's next, you can update that previous node's next any time you want by dereferencing it.
template <typename T>
SinglyLinkedList<T>::SinglyLinkedList(const SinglyLinkedList& obj)
{
Node<T>* tocopy = obj.head;
Node<T>** nextpp = &head; // head is a next. We are now pointing to a pointer to next
while (tocopy) // keep looping until there is no next node to copy
{
*nextpp = new Node<T>(tocopy->data); // copy source and update destination's next
nextpp = &(*nextpp)->next; // advance to point at the next of the node we just added
tocopy= tocopy->next; // get next node to copy
}
count = obj.count;
}
Because this iterates rather than recurses it doesn't eat up Automatic storage (probably the stack) and can keep going until the cows come home.
This logic can also be applied to remove
template <typename T>
void SinglyLinkedList<T>::remove(T item) {
Node<T>** temp = &head; //head is nothing but a next pointer.
// by pointing to where the next is, we don't
// need to track a previous or have special handling
// for the head node
while (*temp){ // because we now have a pointer to a pointer, we need an
// extra dereference
if ((*temp)->data == item){
Node<T>* removable = *temp;
*temp = (*temp)->next;
delete(removable);
count -= 1;
return; // no need for any special magic. Just get out.
} else{
temp = &(*temp)->next; // update the pointer to the next
}
}
// if we got here the node was not found.
throw std::invalid_argument("item not present in list");
}
And following through on head is just a next, we can also gut the destructor:
template <typename T>
SinglyLinkedList<T>::~SinglyLinkedList() {
while(head){ // if head null, list empty
Node<T>* temp = head; // cache so we can delete
head = head->next; // move head
delete temp; //delete removed node
}
}

Related

Copy Constructor Error "Terminate called after throwing an instance of 'int'" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
The task was to create a copy constructor for a Forward_list class, and this is the code I have tried. But it keeps showing an error:
terminate called after throwing an instance of 'int'
I have been editing and changing, but I can't seem to get past that error.
class Forward_list
{
public:
class Node
{
public:
// A node will hold data of type T
T data{};
// next will point to the next node in the list
// we initialise next to nullptr
Node* next = nullptr;
// Because we have already intialised the variables
// the default constructor doesn't need to do anything
Node(){}
// if the constructor is called with just one argument.
Node(T input_data, Node* next_node= nullptr)
{
data = input_data;
next = next_node;
}
// Destructor
~Node(){}
};
private:
// private member variables for Forward_list
unsigned size_ = 0;
Node* head_ = nullptr;
public:
Forward_list(const Forward_list<T>& other);
template <typename T>
Forward_list<T>::Forward_list(const Forward_list& other) {
head_ = nullptr;
Node *prev_node = nullptr;
for(Node *other = head_; other != nullptr; other = other->next) {
Node *new_node = new Node;
new_node->data = other->data;
new_node->next = nullptr;
if (!head_)
head_ = new_node;
else
prev_node->next = new_node;
prev_node = new_node;
}
}
Nothing in this code throws an int. So it has to be in code you have not shown. Perhaps in the constructor of T?
Not that it matters, because your copy constructor does not even run its loop at all, since you are looping through the wrong list. You are starting your loop with this->head_ when you need to start it with other.head_ instead.
Also, the Node converting constructor should take its input_data parameter by const reference, and use a member initialization list, to avoid having to default-construct and then assign the data member in separate operations.
Also, the Forward_list copy constructor can be simplified.
Also, make sure you are following the Rule of 3/5/0, if you are not already doing so (you did not show that code).
Try something more like this:
class Forward_list
{
public:
class Node
{
public:
T data;
Node* next;
Node(const T &input_data, Node* next_node = nullptr);
};
Forward_list() = default;
Forward_list(const Forward_list<T>& other);
Forward_list(Forward_list<T>&& other);
~Forward_list();
Forward_list& operator=(Forward_list<T> other);
...
private:
// private member variables for Forward_list
unsigned size_ = 0;
Node* head_ = nullptr;
};
template <typename T>
Forward_list<T>::Node(const T &input_data, Node* next_node)
: data(input_data), next(next_node)
{
}
template <typename T>
Forward_list<T>::Forward_list(const Forward_list& other) {
Node **new_node = &head_;
for(Node *other_node = other.head_; other_node != nullptr; other_node = other_node->next) {
*new_node = new Node(other->data);
++size_;
new_node = &((*new_node)->next);
}
}
template <typename T>
Forward_list<T>::Forward_list(Forward_list&& other) :
head_(std::exchange(other.head_, nullptr)),
size_(std::exchange(other.size_, 0))
{
}
template <typename T>
Forward_list<T>::~Forward_list() {
Node *node = head_;
while (node) {
Node *next = node->next;
delete node;
node = next;
}
}
template <typename T>
Forward_list<T>& Forward_list<T>::operator=(Forward_list other)
{
std::swap(head_, other.head_);
std::swap(size_, other.size_);
return *this;
}

Fixing memory leaks in a doubly linked list implementation

I read some of the other posts on this topic because there were quite a few, but they didn't really help my situation.
I am getting memory leaks in my implementation of a doubly linked list. I have to make my own so using list is not an option.
here are the two push functions I am using...
template <class T>
void dllist<T>::push_front(T val) {
node* new_node = new node;
new_node->value = val;
new_node->forward = head;
new_node->backward = nullptr;
if (head != nullptr)
head->backward = new_node;
head = new_node;
}
and...
template <class T>
void dllist<T>::push_back(T val) {
node* new_node = new node;
new_node->value = val;
new_node->forward = nullptr;
if (!head)
head = new_node;
else {
node* traveller = head;
while (traveller->forward != nullptr)
traveller = traveller->forward;
traveller->forward = new_node;
new_node->backward = traveller;
}
}
finally, here is my destructor
template <class T>
dllist<T>::~dllist() {
node* current = head;
while (current != nullptr) {
node* forward = current->forward;
delete current;
current = forward;
}
}
In main, I declare an object of type dllist called mylist and I make a few calls to push_front with some integer values and then push_back.
I am using the CRT library to check for leaks and there is a leak at each call to push_back or push_front.
I am confused because I thought I made my destructor correctly. Is there something else Im not seeing?
If anyone could point me in the right direction I'd appreciate it!
Thanks.
MRE
template<class T>
class dllist {
struct node {
T value;
node* forward;
node* backward;
};
node* head;
public:
dllist(); // default constructor
~dllist(); // default destructor
void push_front(T); // push element to the front of the list
void push_back(T); // push element to the back of the list
};
int main() {
{
dllist<int> mylist;
mylist.push_front(10);
mylist.push_front(12);
mylist.push_front(14);
mylist.push_front(16);
mylist.push_front(18);
mylist.push_front(19);
mylist.push_back(11);
mylist.push_back(21);
mylist.push_back(31);
mylist.push_back(41);
mylist.push_back(31);
mylist.push_back(41);
mylist.push_back(222);
}
_CrtDumpMemoryLeaks();
return 0;
}
template <class T>
dllist<T>::dllist() {
head = nullptr;
}

Creating LinkedList exits with return code -11 (SIGSEGV)

So I'm trying to create a Linked List class to understand better how pointers and data structures work but I keep running into a -11 SIGSEGV error. When I looked up the error it said that I might be using dereferenced pointers or accessing an array out of its bounds but neither of those makes sense for my program. I've searched everywhere for similar issues but none of them seem to apply to my program. Can anyone else see what I'm doing wrong?
#include <stdexcept>
#pragma once
using namespace std;
#define NODE typename LinkedList<T>::Node*
template <typename T>
class LinkedList {
public:
void AddHead(const T& data); //Adds new node to the beginning of the list
void AddTail(const T& data); //Adds new node to the end of the list
LinkedList(); //Default constructor
LinkedList(const LinkedList<T>& list); //Copy constructor
struct Node {
/*Individual node that stores the data*/
T data;
Node* prev;
Node* next;
Node(); //Default constructor for node
Node(T _data); //Data constructor for node
Node(T _data, Node* _prev, Node* _next); //Full constructor for node
};
private:
NODE head = nullptr;
NODE tail = nullptr;
unsigned int count;
};
/*Function definitions*/
template <typename T>
void LinkedList<T>::AddHead(const T& data) {
NODE tempRef = new Node(data, nullptr, head);
head->prev = tempRef;
head = tempRef;
delete tempRef;
count++;
}
template <typename T>
void LinkedList<T>::AddTail(const T& data) {
NODE tempRef = new Node(data, tail, nullptr);
tail->next = tempRef;
tail = tempRef;
delete tempRef;
count++;
}
template <typename T>
LinkedList<T>::LinkedList() {
count = 0;
head = nullptr;
tail = nullptr;
}
template <typename T>
LinkedList<T>::LinkedList(const LinkedList<T>& list) {
this->head = list.head;
this->tail = list.tail;
this->count = list.count;
}
/*Node Constructors*/
template <typename T>
LinkedList<T>::Node::Node() {
next = nullptr;
prev = nullptr;
}
template <typename T>
LinkedList<T>::Node::Node(T _data) {
next = nullptr;
prev = nullptr;
data = _data;
}
template <typename T>
LinkedList<T>::Node::Node(T _data, Node* _prev, Node* _next) {
next = _next;
prev = _prev;
data = _data;
}
The both functions AddHead and AddTail have a serious bug because the allocated node is at once deleted
head = tempRef;
delete tempRef;
and
tail = tempRef;
delete tempRef;
So the pointers head and tail have invalid values.
Moreover the functions do not update tail and head correspondingly in each function.
And initially the both pointers are equal to nullptr. So these statements
head->prev = tempRef;
and
tail->next = tempRef;
result in undefined behavior.
The function AddHead can be defined the following way
template <typename T>
void LinkedList<T>::AddHead(const T& data) {
NODE tempRef = new Node(data, nullptr, head);
if ( head == nullptr )
{
head = tail = tempRef;
}
else
{
head = head->prev = tempRef;
}
count++;
}
And the function AddTail can look like
template <typename T>
void LinkedList<T>::AddTail(const T& data) {
NODE tempRef = new Node(data, tail, nullptr);
if ( tail == nullptr )
{
tail = head = tempRef;
}
else
{
tail = tail->next = tempRef;
}
count++;
}
The copy constructor (and the copy assignment operator) either should be defined as deleted or shall make a deep copy of the list passed as the argument.
Otherwise two lists will try to delete the same nodes two times (in the forgotten by you destructor).
The structure Node should be declared as a private class member.
You delete the nodes you add to the list in both AddTail and AddHead. This leaves pointers to garbage in the list.
Also, it's not clear how to use your linked list. You cannot call AddHead if head is nullptr (because AddHead dereferences head) and you cannot call AddTail if tail is nullptr. Since your constructor sets both head and tail equal to nullptr, what can you do next?
If it's legal for head to be nullptr, why does AddHead do head->prev = tempRef; without checking if head is nullptr?
I would strongly urge you to document your code. For example, what are the required preconditions for AddHead to be called? Is it supposed to be safe to call if head is nullptr or is it a requirement that it not be? Why is that not documented?

Making a copy constructor more flexible for ADT queue

I have constructed a copy constructor for an ADT queue. The copy constructor works fine. I would want to improve my code, but I don't really know how to shorten it to make it more flexible. Code is given below:
template <typename T>
Queue <T>::Queue(const Queue & other)
{
if (other.first == nullptr)
{
first = nullptr;
nrOfElements = 0;
}
else
{
Node* saveFirst;
Node* walker;
first = other.first;
walker = new Node(first->data);
saveFirst = walker;
while (first->next != nullptr)
{
walker->next = new Node(first->next->data);
walker = walker->next;
first = first->next;
}
walker->next = nullptr;
first = saveFirst;
}
this->nrOfElements = other.nrOfElements;
}
The class Queue also contains an inner private Node class which contains the pointers first, next, etc:
private:
int nrOfElements;
class Node
{
public:
Node* next;
T data;
Node(T data)
{
this->data = data;
}
};
Node* first;
So, I would appreciate any suggestions/examples of how the copy constructor code above could be improved, as I'm a bit lost on the task.
try this one
may be in easier than your code
template <typename T>
Queue <T>::Queue(const Queue & other)
{
Front =NULL;Rear=NULL;Count=0;
Node *p= other.Front;
while(p!=NULL){
EnQueue(p->GetData());
Rear->SetData(p->GetData());
p=p->next;
}
}
First we set NULL value to Front & Rear and 0 for Count second make new Node to get the data from every Node in old Queue and copy it to the new Queue.

Queue: Dequeue function crashes program

I am attempting to make a queue in c++ using a double linked list. I Have not fully tested everything since i am stuck at the step where you dequeue. I attempted to create a temp node, and move around stuff so when I call delete on the head node in the queue (called queue), and then set the head to a temp node which is the next element, (you can see in the code) but when I call delete, is where it crashes, according to MS Visual studios 2013. Also to add how weird this is, following the stack called, after delete is called, setPrev is called and set the prev node and crashes there. Now I never call this function during any of my destructors deletes so any help will do. I will try my best to understand any answers but I am still new to c++ terminology. Below is my code. Oh one last thing, in main, all I did was call enqueue once, then dequeue once, then delete
Node Class
...
#ifndef TSDNODE_H
#define TSDNODE_H
template <class T>
class DNode
{
private:
DNode<T>* next;
DNode<T>* prev;
T data;
public:
DNode(T);
void setNext(DNode<T>* next);
void setPrev(DNode<T>* prev);
DNode<T>* getNext() const;
DNode<T>* getPrev() const;
T getData() const;
void setData(T data);
~DNode();
};
template <class T>
DNode<T>::DNode(T data)
{
this->next = nullptr;
this->data = data;
this->prev = nullptr;
}
template <class T>
void DNode<T>::setNext(DNode<T>* next)
{
this->next = next;
}
template <class T>
void DNode<T>::setPrev(DNode<T>* prev)
{
this->prev = prev;
}
template <class T>
DNode<T>* DNode<T>::getNext() const
{
return this->next;
}
template <class T>
DNode<T>* DNode<T>::getPrev() const
{
return this->prev;
}
template <class T>
T DNode<T>::getData() const
{
return this->data;
}
template <class T>
void DNode<T>::setData(T data)
{
this->data = data;
}
template <class T>
DNode<T>::~DNode()
{
delete this->next;
delete this->prev;
this->next = nullptr;
this->prev = nullptr;
}
#endif /* TSDNODE_H */
....
Queue Class
....
#ifndef TSQUEUE_H
#define TSQUEUE_H
#include "TSDNode.h"
#include <string>
template <class T>
class Queue
{
private:
DNode<T>* queue;
DNode<T>* tail;
int size;
public:
Queue();
void enqueue(T data);
T dequeue();
~Queue();
};
template <class T>
Queue<T>::Queue()
{
this->queue = nullptr;
this->tail = this->queue;
size = 0;
}
template <class T>
void Queue<T>::enqueue(T data)
{
if (this->tail != NULL)
{
this->tail->setNext(new DNode<T>(data));
this->tail->getNext()->setPrev(this->tail);
this->tail = this->tail->getNext();
}
else
{
this->queue = new DNode<T>(data);
this->tail = this->queue;
}
size++;
}
template <class T>
T Queue<T>::dequeue()
{
T data;
if (this->queue == nullptr)
{
delete this->tail;
delete this->queue;
this->tail = nullptr;
std::string ex = "Exception: Empty Queue\n";
throw ex;
}
else if (this->queue != nullptr)
{
data = this->queue->getData();
DNode<T>* node = this->queue->getNext();
this->queue->setNext(nullptr);
this->queue->setPrev(nullptr);
node->setPrev(nullptr);
//--------------------------------------------------- crashes here
delete this->queue;
this->queue = node;
}
size--;
return data;
}
template <class T>
Queue<T>::~Queue()
{
delete this->queue;
this->queue = nullptr;
this->tail = nullptr;
}
#endif /* TSQUEUE_H */
In your DNode destructor, you don't want to delete the next and prev nodes. You only want to delete this node, not everything it links to.
Remove these lines
delete this->next;
delete this->prev;
Edit: Actually this isn't your problem, because you are clearing out the next and prev values before you delete the node. I still think it is better to not automatically delete the whole chain, but as long as you are consistent with how you handle node deletion it should still work.
You actually problem is that when you dequeue the last node, you still try to set the next pointer of the next node in this line:
node->setPrev(nullptr);
//--------------------------------------------------- crashes here
At this point node is nullptr, so trying to access node->next causes a crash. A simple if test is all you need
if (node != nullptr)
node->setPrev(nullptr);
//--------------------------------------------------- no longer crashes here
Edit 2:
Also note that in the case where the next node in the queue is nullptr, you also want to set the tail to nullptr.