I am having some trouble making the appropriate changes from a post I made on code review. Here is the original post I made here. Specifically, I am at the point where I am revising my insertPosition function.
Previously my function was like this:
template <class T>
void DoubleLinkedLists<T>::insertPosition(int pos, const T& theData) {
Node* prev = new Node;
Node* current = head;
Node* newNode = new Node;
for(int i = 1; i < pos; i++) {
prev = current;
current = current->next;
}
newNode->data = theData;
prev->next = newNode;
newNode->next = current;
}
But now, from what I have been told to do was make it more like this:
Node* cur_node = head;
int i = 0;
while (cur_node) {
if (i++ == pos) {
// do the deed
}
cur_node = cur_node->next;
}
I am not sure what to write in the // do the deed part. What I have tried is this:
template <class T>
void DoubleLinkedLists<T>::insertPosition(int pos, const T& theData) {
Node* current = head;
int i = 0;
while(current) {
if(i++ == pos) {
Node* newNode = new Node;
newNode->data = theData;
newNode->next = newNode->previous;
}
current = current->next;
}
}
But I do not get the code to work at all when I test it out. There are also various other things I need to change I am sure but I would like to get a second opinion of my code I have thus far.
Here is the header file:
#ifndef DoubleLinkedLists_h
#define DoubleLinkedLists_h
template <class T>
class DoubleLinkedLists {
private:
struct Node {
T data;
Node* next;
Node* previous;
};
Node* head;
Node* tail;
public:
// Constructors
DoubleLinkedLists() : head(nullptr), tail(nullptr) {} // empty constructor
DoubleLinkedLists(DoubleLinkedLists const& value); // copy constructor
DoubleLinkedLists<T>(DoubleLinkedLists<T>&& move) noexcept; // move constuctor
DoubleLinkedLists<T>& operator=(DoubleLinkedLists&& move) noexcept; // move assignment operator
~DoubleLinkedLists(); // destructor
// Overload operators
DoubleLinkedLists& operator=(DoubleLinkedLists const& rhs);
friend std::ostream& operator<<(std::ostream& str, DoubleLinkedLists<T> const& data) {
data.display(str);
return str;
}
// Member functions
void swap(DoubleLinkedLists& other) noexcept;
void createNode(const T& theData);
void createNode(T&& theData);
void display(std::ostream& str) const;
void insertHead(const T& theData);
void insertTail(const T& theData);
void insertPosition(int pos, const T& theData);
void deleteHead();
void deleteTail();
void deletePosition(int pos);
bool search(const T& x);
};
template <class T>
DoubleLinkedLists<T>::DoubleLinkedLists(DoubleLinkedLists const& value) : head(nullptr), tail(nullptr) {
for(Node* loop = value->head; loop != nullptr; loop = loop->next) {
createNode(loop->data);
}
}
template <class T>
DoubleLinkedLists<T>::DoubleLinkedLists(DoubleLinkedLists<T>&& move) noexcept : head(nullptr), tail(nullptr) {
move.swap(*this);
}
template <class T>
DoubleLinkedLists<T>& DoubleLinkedLists<T>::operator=(DoubleLinkedLists<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
DoubleLinkedLists<T>::~DoubleLinkedLists() {
while(head != nullptr) {
deleteHead();
}
}
template <class T>
DoubleLinkedLists<T>& DoubleLinkedLists<T>::operator=(DoubleLinkedLists const& rhs) {
DoubleLinkedLists copy(rhs);
swap(copy);
return *this;
}
template <class T>
void DoubleLinkedLists<T>::swap(DoubleLinkedLists<T>& other) noexcept {
using std::swap;
swap(head, other.head);
swap(tail, other.tail);
}
template <class T>
void DoubleLinkedLists<T>::createNode(const T& theData) {
Node* newData = new Node;
newData->data = theData;
newData->next = nullptr;
if(head == nullptr) {
newData->previous = nullptr;
head = newData;
tail = newData;
}
else {
newData->previous = tail;
tail->next = newData;
tail = newData;
}
}
template <class T>
void DoubleLinkedLists<T>::createNode(T&& theData) {
Node* newData = new Node;
newData->data = std::move(theData);
newData->next = nullptr;
if(head == nullptr) {
newData->previous = nullptr;
head = newData;
tail = newData;
}
else {
newData->previous = tail;
tail->next = newData;
tail = newData;
}
}
template <class T>
void DoubleLinkedLists<T>::insertHead(const T& theData) {
Node* newNode = new Node;
newNode->data = theData;
newNode->next = head;
head->previous = newNode;
head = newNode;
}
template <class T>
void DoubleLinkedLists<T>::insertTail(const T& theData) {
Node* newNode = new Node;
newNode->data = theData;
newNode->previous = tail;
tail->next = newNode;
tail = newNode;
}
//template <class T>
//void DoubleLinkedLists<T>::insertPosition(int pos, const T& theData) {
// Node* prev = new Node;
// Node* current = head;
// Node* newNode = new Node;
//
// for(int i = 1; i < pos; i++) {
// prev = current;
// current = current->next;
// }
// newNode->data = theData;
// prev->next = newNode;
// newNode->next = current;
//}
template <class T>
void DoubleLinkedLists<T>::insertPosition(int pos, const T& theData) {
Node* current = head;
int i = 0;
while(current) {
if(i++ == pos) {
Node* newNode = new Node;
newNode->data = theData;
newNode->next = newNode->previous;
}
current = current->next;
}
}
template <class T>
void DoubleLinkedLists<T>::display(std::ostream &str) const {
for(Node* loop = head; loop != nullptr; loop = loop->next) {
str << loop->data << "\t";
}
str << "\n";
}
template <class T>
void DoubleLinkedLists<T>::deleteHead() {
Node* old = head;
head = head->next;
delete old;
}
template <class T>
void DoubleLinkedLists<T>::deleteTail() {
Node* prev = nullptr;
Node* current = head;
while(current->next != nullptr) {
prev = current;
current = current->next;
}
tail = prev;
prev->next = nullptr;
delete current;
}
template <class T>
void DoubleLinkedLists<T>::deletePosition(int pos) {
Node* prev = new Node;
Node* current = head;
for(int i = 1; i < pos; i++) {
prev = current;
current = current->next;
}
prev->next = current->next;
}
template <class T>
bool DoubleLinkedLists<T>::search(const T &x) {
Node* current = head;
while(current != nullptr) {
if(current->data == x) {
return true;
}
current = current->next;
}
return false;
}
#endif /* DoubleLinkedLists_h */
Here is the main.cpp file to test the above implementation:
#include <iostream>
#include "DoubleLinkedLists.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////// Double Linked List //////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
DoubleLinkedLists<int> obj;
obj.createNode(2);
obj.createNode(4);
obj.createNode(6);
obj.createNode(8);
obj.createNode(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------Displaying All nodes---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Inserting At Start----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertHead(50);
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-----------------Inserting At End-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertTail(20);
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-------------Inserting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertPosition(5,60);
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Deleting At Start-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteHead();
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Deleting At End-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteTail();
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"--------------Deleting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deletePosition(4);
std::cout << obj << std::endl;
std::cout << std::endl;
obj.search(8) ? printf("Yes"):printf("No");
return 0;
}
Update:
This is what I have done so far, I am pass in the data into a new node and then link previous node with the next node. Although, the code runs but nothing actually gets inserted into a position so I believe it does not even go through the while loop. I am not sure what the problem is.
template <class T>
void DoubleLinkedLists<T>::insertPosition(int pos, const T& theData) {
Node* current = head;
int i = 0;
while(current) {
if(i++ == pos) {
Node* newNode = new Node;
newNode->data = theData;
newNode->previous = newNode->next;
}
current = current->next;
}
}
So...
template <class T>
void DoubleLinkedLists<T>::insertPosition(int pos, const T& theData) {
Node* current = head;
int i = 0;
while (current != nullptr) {
if (i++ == pos) {
Node* newNode = new Node;
newNode->data = theData;
// Let's do the wiring
newNode->previous = current->previous;
newNode->next = current;
if (newNode->previous != nullptr) { // If the node is inserted at the end
newNode->previous->next = newNode;
}
current->previous = newNode;
return;
}
current = current->next;
}
}
Related
I am trying to figure out what is wrong with my cpp code, and i need your help!
valgrind Output:
the error occurs here (in the test file):
list = list.apply(getLen);
the function getLen:
string getLen(string str)
{
return std::to_string(str.length());
}
the generic function apply:
template<class T>
template<class Operation>
SortedList<T> SortedList<T>::apply(Operation operation) const{//TODO: 6 blocks are indirectly lost.
Node<T>* current_node_to_check = head;
SortedList<T> new_sorted_list;
for (int i = 0; i < list_length; ++i) {
T result = operation(current_node_to_check->info);
new_sorted_list.insert(result);
current_node_to_check = current_node_to_check->next;
}
return new_sorted_list;
}
the Node struct implementation:
template<class T>
struct Node{
T info;
Node<T>* next;
explicit Node(const T& new_info) : info(new_info), next(nullptr){}
};
the test file:
#include <iostream>
#include "SortedList.h"
#include "examDetails.h"
using std::cout;
using std::endl;
using std::string;
using namespace mtm;
#define TEST(num) cout << endl << "TEST " << (num) << endl;
string getLen(string str)
{
return std::to_string(str.length());
}
bool isTrollLink(const ExamDetails& exam) {
return (exam.getLink().find("tinyurl") != string::npos);
}
template<class T>
void printList(SortedList<T> list) {
for (auto it = list.begin(); !(it == list.end()); ++it) {
cout << *it << endl;
}
cout << endl;
}
int main()
{
.
.
.
TEST("1.5")
SortedList<string> lst1 = SortedList<string>();
lst1.insert("Charlie");
lst1.insert("Bob");
lst1.insert("Alice");
lst1.insert("Donald");
printList(lst1);
TEST("1.6")
SortedList<ExamDetails> lst2;
lst2.insert(exam1);
lst2.insert(exam2);
printList(lst2);
TEST("1.7")
SortedList<string> lst3 = lst1;
printList(lst3);
TEST("1.8")//TODO: 6 blocks are indirectly lost.
lst3 = lst3.apply(getLen);
printList(lst3);
TEST("1.9")
lst3.remove(lst3.begin());
printList(lst3);
TEST("1.10")
SortedList<ExamDetails> lst4 = lst2.filter(isTrollLink);
printList(lst2);
cout << "----------" << endl;
printList(lst4);
return 0;
}
the generic class file:
#ifndef NEW_SORTED_LIST_SORTEDLIST_H
#define NEW_SORTED_LIST_SORTEDLIST_H
#include <stdexcept>
using std::cout;
using std::endl;
namespace mtm {
template<class T>
struct Node{
T info;
Node<T>* next;
explicit Node(const T& new_info) : info(new_info), next(nullptr){}
};
template<class T>
class SortedList {
private:
Node<T>* head;
int list_length;
static const int empty = 0;
void deleteNodes();
public:
class const_iterator;
SortedList();
~SortedList();
SortedList(const SortedList &to_copy);
SortedList& operator=(const SortedList &to_assign);
void insert(const T &to_insert);
void remove(const const_iterator& iterator);
int length() const;
template<class Condition>
SortedList filter(Condition condition) const;
template<class Operation>
SortedList apply(Operation operation) const;
const_iterator begin() const;
const_iterator end() const;
};
template<class T>
class SortedList<T>::const_iterator{
const SortedList<T>* sortedListPointer;
int index;
const_iterator(const SortedList<T>* sortedListPointer, int index) : sortedListPointer(sortedListPointer),
index(index){}
friend class SortedList<T>;
static const int first = 1;
public:
const_iterator(const const_iterator&) = default;
const_iterator& operator=(const const_iterator&) = default;
const T& operator*(){
if (index > sortedListPointer->length()+1 || index<0){
throw std::out_of_range("error: iterator out of range");//TODO
}
Node<T>* current = sortedListPointer->head;
for (int i = 1; i < index; ++i) {
current = current->next;
}
return current->info;
}
const_iterator& operator++() {
++index;
if (index > sortedListPointer->length()+1){
throw std::out_of_range("error: iterator out of range");//TODO
}
return *this;
}
const_iterator operator++(int){
SortedList<T>::const_iterator result = *this;
++*this;
return result;
}
bool operator==(const const_iterator& it) const{
return (index == it.index);
}
};
template<class T>
typename SortedList<T>::const_iterator SortedList<T>::begin() const{
return const_iterator(this, const_iterator::first);
}
template<class T>
typename SortedList<T>::const_iterator SortedList<T>::end() const{
return const_iterator(this, this->length()+1);
}
template<class T>
SortedList<T>::SortedList() : head(nullptr), list_length(empty){}
template<class T>
SortedList<T>::~SortedList() {
deleteNodes();
}
template<class T>
SortedList<T>::SortedList(const SortedList& to_copy){
Node<T>* current_to_copy = to_copy.head;
Node<T>* current = nullptr;
Node<T>* new_head;
if (to_copy.list_length == 0){
return;
}else{
Node<T>* new_node = new Node<T>(current_to_copy->info);
//exception
//new_node->info = current_to_copy->info;
//new_node->next = nullptr;
current = new_node;
current_to_copy = current_to_copy->next;
new_head = current;
}
while (current_to_copy){
Node<T>* new_node = new Node<T>(current_to_copy->info);
//exception
//new_node->info = current_to_copy->info;
//new_node->next = nullptr;
current->next = new_node;
current = current->next;
current_to_copy = current_to_copy->next;
}
list_length = to_copy.list_length;
head = new_head;
}
template<class T>
void SortedList<T>::deleteNodes(){
if (list_length == empty){
head = nullptr;
return;
}
Node<T>* current = head->next;
for (int i = 1; i < list_length; ++i) {
Node<T>* previous = head;
Node<T>* temp = current->next;
delete current;
current = temp;
previous->next = current;
}
delete head;
head = nullptr;
list_length = empty;
}
template<class T>
SortedList<T>& SortedList<T>::operator=(const SortedList &to_assign){
if (this == &to_assign){
return *this;
}
head = nullptr;
Node<T>* current_to_assign = to_assign.head;
Node<T>* current;
Node<T>* new_head;
if (current_to_assign){
Node<T>* first_node = new Node<T>(current_to_assign->info);
current = first_node;
current_to_assign = current_to_assign->next;
new_head = first_node;
}else{
deleteNodes();
head = nullptr;
return *this;
}
while (current_to_assign){
Node<T>* new_node = new Node<T>(current_to_assign->info);
current->next = new_node;
current = current->next;
current_to_assign = current_to_assign->next;
}
head = new_head;
list_length = to_assign.list_length;
return *this;
}
template<class T>
void SortedList<T>::insert(const T &to_insert){
Node<T>* new_node = new Node<T>(to_insert);
Node<T>* current = head;
if (!current){
head = new_node;
list_length++;
return;
}
Node<T>* previous = head;
if (current->info < to_insert){
current = current->next;
}else{
new_node->next = current;
head = new_node;
list_length++;
return;
}
while (current){
if (current->info < to_insert){
current = current->next;
previous = previous->next;
}else{
new_node->next = current;
previous->next = new_node;
list_length++;
return;
}
}
previous->next = new_node;
list_length++;
}
template<class T>
void SortedList<T>::remove(const SortedList<T>::const_iterator& iterator){
if (list_length == 1){
list_length--;
delete head;
}
int index = iterator.index;
if (index == 1){
Node<T>* temp = head->next;
delete head;
head = temp;
list_length--;
return;
}
Node<T>* current = head;
Node<T>* previous = nullptr;
for (int i = 1; i < index-1; ++i) {
if ((i+1) == index-1){
previous = current;
}
current = current->next;
}
previous->next = current->next;
delete current;//TODO destructor(?)
list_length--;
}
template<class T>
int SortedList<T>::length() const{
return list_length;
}
template<class T>
template<class Condition>
SortedList<T> SortedList<T>::filter(Condition condition) const{
Node<T>* current_node_to_check = head;
SortedList<T> new_sorted_list;
for (int i = 0; i < list_length; ++i) {
if (condition(current_node_to_check->info)){
new_sorted_list.insert(current_node_to_check->info);
}
current_node_to_check = current_node_to_check->next;
}
return new_sorted_list;
}
template<class T>
template<class Operation>
SortedList<T> SortedList<T>::apply(Operation operation) const{//TODO: 6 blocks are indirectly lost.
Node<T>* current_node_to_check = head;
SortedList<T> new_sorted_list;
for (int i = 0; i < list_length; ++i) {
T result = operation(current_node_to_check->info);
new_sorted_list.insert(result);
current_node_to_check = current_node_to_check->next;
}
return new_sorted_list;
}
}
#endif //NEW_SORTED_LIST_SORTEDLIST_H
without the test 1.8, the code works great with no errors at all!
What should I do to fix it?
thanks
You allocated a SortedList<string> object in main() which allocated memory and never freed it.
The other blocks belong to the std::string objects inside the list. They are only lost because the list holding them lost track of them.
When doing your analysis, don't worry about the 6 indirectly lost blocks, focus on the one directly lost one.
Almost certainly this is a violation of the "Rule of Five". Your SortedList does an allocation in its constructor and doesn't properly manage that allocation in its move-assignment operator.
Looking at your code in the copy assignment operator, this line is causing the leak
head = nullptr;
It shouldn't be needed, you later call deleteNodes() which will do that anyway, and by erasing head beforehand you prevent deleteNodes() from doing its work.
I am having some trouble with this function I wrote to delete at some position in a double linked list. I feel like I am leaking memory and I am not doing this property for a double linked list.
Here is the code:
template <class T>
void DoubleLinkedLists<T>::deletePosition(int pos) {
Node* prev = new Node;
Node* current = head;
for(int i = 1; i < pos; i++) {
prev = current;
current = current->next;
}
prev->next = current->next;
}
This is pretty much what I did for a single linked list so I know this is not right. If anyone has any suggestions on how to do this for a double linked list I would really appreciate it.
EDIT:
I think this works correctly now:
template <class T>
void DoubleLinkedLists<T>::deletePosition(int pos) {
Node* temp = nullptr;
Node* current = head;
for(int i = 1; i < pos; i++) {
temp = current;
current = current->next;
}
temp->previous = current->previous;
temp->next = current->next;
}
Here is the entire code:
#ifndef DoubleLinkedLists_h
#define DoubleLinkedLists_h
template <class T>
class DoubleLinkedLists {
private:
struct Node {
T data;
Node* next;
Node* previous;
};
Node* head;
Node* tail;
public:
// Constructors
DoubleLinkedLists() : head(nullptr), tail(nullptr) {} // empty constructor
DoubleLinkedLists(DoubleLinkedLists const& value); // copy constructor
DoubleLinkedLists<T>(DoubleLinkedLists<T>&& move) noexcept; // move constuctor
DoubleLinkedLists<T>& operator=(DoubleLinkedLists&& move) noexcept; // move assignment operator
~DoubleLinkedLists(); // destructor
// Overload operators
DoubleLinkedLists& operator=(DoubleLinkedLists const& rhs);
friend std::ostream& operator<<(std::ostream& str, DoubleLinkedLists<T> const& data) {
data.display(str);
return str;
}
// Member functions
void swap(DoubleLinkedLists& other) noexcept;
void push(const T& theData);
void push(T&& theData);
void display(std::ostream& str) const;
void insertHead(const T& theData);
void insertTail(const T& theData);
void insertPosition(int pos, const T& theData);
void deleteHead();
void deleteTail();
void deletePosition(int pos);
bool search(const T& x);
};
template <class T>
DoubleLinkedLists<T>::DoubleLinkedLists(DoubleLinkedLists const& value) : head(nullptr), tail(nullptr) {
for(Node* loop = value->head; loop != nullptr; loop = loop->next) {
push(loop->data);
}
}
template <class T>
DoubleLinkedLists<T>::DoubleLinkedLists(DoubleLinkedLists<T>&& move) noexcept : head(nullptr), tail(nullptr) {
move.swap(*this);
}
template <class T>
DoubleLinkedLists<T>& DoubleLinkedLists<T>::operator=(DoubleLinkedLists<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
DoubleLinkedLists<T>::~DoubleLinkedLists() {
while(head != nullptr) {
deleteHead();
}
}
template <class T>
void DoubleLinkedLists<T>::swap(DoubleLinkedLists<T> &other) noexcept {
using std::swap;
swap(head,other.head);
swap(tail,other.tail);
}
template <class T>
void DoubleLinkedLists<T>::push(const T& theData) {
Node* newNode = new Node;
newNode->data = theData;
newNode->previous = tail;
if(head == nullptr) {
head = newNode;
}
else {
tail->next = newNode;
}
tail = newNode;
}
template <class T>
void DoubleLinkedLists<T>::push(T&& theData) {
Node* newNode = new Node;
newNode->data = theData;
newNode->previous = tail;
if(head == nullptr) {
head = newNode;
}
else {
tail->next = newNode;
}
tail = newNode;
}
template <class T>
void DoubleLinkedLists<T>::display(std::ostream &str) const {
for(Node* loop = head; loop != nullptr; loop = loop->next) {
str << loop->data << "\t";
}
str << "\n";
}
template <class T>
void DoubleLinkedLists<T>::insertHead(const T &theData) {
Node* newNode = new Node;
newNode->data = theData;
newNode->next = head;
head->previous = newNode;
head = newNode;
}
template <class T>
void DoubleLinkedLists<T>::insertTail(const T &theData) {
Node* newNode = new Node;
newNode->data = theData;
newNode->previous = tail;
tail->next = newNode;
tail = newNode;
}
template <class T>
void DoubleLinkedLists<T>::insertPosition(int pos, const T &theData) {
if (pos < 0) {
throw std::invalid_argument("pos is not a valid index");
}
Node* current = head;
Node* previous = nullptr;
while(pos-- > 0) {
if(!current) {
throw std::invalid_argument("pos is not a valid index");
}
previous = current;
current = current->next;
}
Node* newNode = new Node;
newNode->data = theData;
newNode->previous = previous;
newNode->next = current;
if(newNode->previous) {
newNode->previous->next = newNode;
}
else {
head = newNode;
}
if(newNode->next) {
newNode->next->previous = newNode;
}
else {
tail = newNode;
}
}
template <class T>
void DoubleLinkedLists<T>::deleteHead() {
if (head != nullptr) {
Node* old = head;
head = head->next;
delete old;
}
else {
throw std::invalid_argument("the list is empty!");
}
}
template <class T>
void DoubleLinkedLists<T>::deleteTail() {
if(head != nullptr) {
Node* prev = nullptr;
Node* current = head;
while(current->next != nullptr) {
prev = current;
current = current->next;
}
tail = prev;
prev->next = nullptr;
delete current;
}
else {
throw std::invalid_argument("The list is already empty, nothing to delete.");
}
}
template <class T>
void DoubleLinkedLists<T>::deletePosition(int pos) {
Node* temp = nullptr;
Node* current = head;
for(int i = 1; i < pos; i++) {
temp = current;
current = current->next;
}
temp->previous = current->previous;
temp->next = current->next;
}
template <class T>
bool DoubleLinkedLists<T>::search(const T &x) {
Node* current = head;
while(current != nullptr) {
if(current->data == x) {
return true;
}
current = current->next;
}
return false;
}
#endif /* DoubleLinkedLists_h */
And here is the main.cpp file that tests it:
#include <iostream>
#include "DoubleLinkedLists.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////// Double Linked List //////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
DoubleLinkedLists<int> obj;
obj.push(2);
obj.push(4);
obj.push(6);
obj.push(8);
obj.push(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------Displaying All nodes---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Inserting At Start----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertHead(50);
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-----------------Inserting At End-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertTail(20);
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-------------Inserting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertPosition(5,60);
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Deleting At Start-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteHead();
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Deleting At End-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteTail();
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"--------------Deleting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deletePosition(5);
std::cout << obj << std::endl;
std::cout << std::endl;
obj.search(8) ? printf("Yes"):printf("No");
return 0;
}
So you would need to do something like this. Note that your code does not handle the case of an index out of range (i.e. the position specified is either negative or is longer the list). It looked like you don't maintain a count of your list length (in the linked code) so I added a check for current != nullptr into the for loop as well as after the for loop to handle the case of the pos being longer than the list. In that case, now the code will do nothing, but you could throw an out of range exception or something like that to indicate the invalid condition. In the case of removing the head you also need to take care to fix up the head pointer. I am assuming you might have a tail pointer as well, so you need to add checks to see if you are removing the tail and fix that up as well.
Note
I didn't compile this and so there may be a typo or two, but it should at least point you in the right direction.
void DoubleLinkedLists<T>::deletePosition(int pos) {
if (pos < 0) {} // Should do something in this case
Node* current = head;
// Added null check to keep from continuing past the end of the list
for(int i = 1; i < pos && current != nullptr; i++) {
current = current->next;
}
if (current != nullptr)
{
// If we are at the head, there isn't a previous
if (current != head)
{
current->previous->next = current->next;
}
else
{
// In this case, we are removing the head, need to reset head to the next Node
head = current->next;
}
if (current->next != nullptr)
{
current->next->previous = current->previous;
}
else if (current == tail)
{
// In this case we are removing the tail, need to reset tail pointer
tail = current->previous;
}
delete current; // Cleans up the node we are deleting
}
}
As the title suggests, I am trying to learn data structures and I am starting with a linked list. I decided to make it generic since I thought it would be useful to do to handle other data types.
I am getting these associated errors:
I am not sure what I am doing wrong and I cannot identify the error. Here is my code starting with the header file:
#ifndef LinkedList_hpp
#define LinkedList_hpp
template<class T>
struct Node {
T data;
Node<T>* next;
};
template<class T>
class SingleLinkedList {
private:
Node<T>* head, tail;
public:
SingleLinkedList();
void createNode(const T& theData);
void display();
void insert_start(const T& theData);
void insert_position(int pos, const T& theData);
void delete_first();
void delete_last();
void delete_position(int pos);
Node<T>* search(Node<T>* head, const T& target);
};
#endif /* LinkedList_hpp */
Now here is the associated .cpp file:
#include "LinkedList.hpp"
#include <iostream>
template<class T>
SingleLinkedList<T>::SingleLinkedList() {
head = nullptr;
tail = nullptr;
}
template<class T>
void SingleLinkedList<T>::createNode(const T& theData) {
Node<T>* temp = new Node<T>;
temp->data = theData;
temp->next = nullptr;
if(head == nullptr) {
head = temp;
tail = temp;
temp = nullptr;
}
else {
tail->next = temp;
tail = temp;
}
}
template<class T>
void SingleLinkedList<T>::display() {
Node<T>* temp = new Node<T>;
temp = head;
while(temp != nullptr) {
std::cout << temp->data << "\t";
temp = temp->next;
}
}
template<class T>
void SingleLinkedList<T>::insert_start(const T& theData) {
Node<T>* temp = new Node<T>;
temp->data = theData;
temp->next = head;
head = temp;
}
template<class T>
void SingleLinkedList<T>::insert_position(int pos, const T &theData) {
Node<T>* previous = new Node<T>;
Node<T>* current = new Node<T>;
Node<T>* temp = new Node<T>;
temp = head;
for(int i = 1; i < pos; i++) {
previous = current;
current = current->next;
}
temp->data = theData;
previous->next = temp;
temp->next = current;
}
template<class T>
void SingleLinkedList<T>::delete_first() {
Node<T>* temp = new Node<T>;
temp = head;
head = head->next;
delete temp;
}
template<class T>
void SingleLinkedList<T>::delete_last() {
Node<T>* previous = new Node<T>;
Node<T>* current = new Node<T>;
current = head;
while(current->next != nullptr) {
previous = current;
current = current->next;
}
tail = previous;
previous->next = nullptr;
delete current;
}
template<class T>
void SingleLinkedList<T>::delete_position(int pos) {
Node<T>* previous = new Node<T>;
Node<T>* current = new Node<T>;
current = head;
for(int i = 1; i < pos; i++) {
previous = current;
current = current->next;
}
previous->next = current->next;
}
And finally here is the main.cpp file where I attempt to test the code:
#include <iostream>
#include "LinkedList.hpp"
int main(int argc, const char * argv[]) {
SingleLinkedList<int> obj;
obj.createNode(2);
obj.createNode(4);
obj.createNode(6);
obj.createNode(8);
obj.display();
return 0;
}
You need to put the implementation of your member functions into the header file.
I am having trouble implementing this with the class I have. So far as a linkedlist of type int or string it works great, but I am not sure how to navigate the list if I initialize it like
linkedlist<linkedlist<int>> nums;
From my program it seems that the head of each secondary list would be an entry in the primary, but my question is how would I navigate it?. For example how would I print all the values of each linkedlist, I am sure I am making this more difficult than it it, but any help would be appreciated.
/* Node Class */
template <typename T>
class Node {
public:
T data;
Node* next;
Node* previous;
Node(T data);
Node();
T getData();
};
template <typename T>
Node<T>::Node() {
this->next = NULL;
this->previous = NULL;
}
template <typename T>
Node<T>::Node(T data) {
this->data = data;
}
template <typename T>
T Node<T>::getData() {
return this->data;
}
/* Linked List: */
template <typename T>
class linkedlist {
private:
Node<T>* head;
Node<T>* tail;
int list_size;
public:
linkedlist();
T getHead();
T getTail();
int size();
void addnodetail(T);
void addnodehead(T);
void push(T);
T pop();
//T* peek();
bool isEmpty() const {
return head == NULL;
}
//T* get(int index);
void printlist();
void printListBackwards();
~linkedlist();
};
template <typename T>
linkedlist<T>::linkedlist() {
this->head = NULL;
this->tail = NULL;
this->list_size = 0;
}
template <typename T>
T linkedlist<T>::getHead() {
return this->head->data;
}
template <typename T>
T linkedlist<T>::getTail() {
return this->tail->data;
}
template <class T>
int linkedlist<T>::size() {
return this->list_size;
}
template <typename T>
void linkedlist<T>::addnodetail(T input) {
Node<T>* newnode = new Node<T>(input);
newnode->next = NULL;
newnode->previous = NULL;
if (this->head == NULL) {
this->head = newnode;
this->tail = this->head;
this->list_size = this->list_size + 1;
} else {
this->tail->next = newnode;
newnode->previous = this->tail;
this->tail = newnode;
this->list_size = this->list_size + 1;
}
}
template <typename T>
void linkedlist<T>::addnodehead(T input) {
Node<T>* newnode = new Node<T>(input);
newnode->next = NULL;
newnode->previous = NULL;
if (this->head == NULL) {
this->head = newnode;
this->tail = this->head;
this->list_size = this->list_size + 1;
} else {
this->head->previous = newnode;
newnode->next = this->head;
this->head = newnode;
this->list_size = this->list_size + 1;
}
}
template <typename T>
void linkedlist<T>::push(T input) {
this->addnodehead(input);
}
template <typename T>
T linkedlist<T>::pop() {
Node<T>* temp = this->head;
// T* temp = this->head;
this->head = this->head->next;
this->head->previous = NULL;
this->list_size = this->list_size - 1;
return temp->data;
}
/*
template <class T>
T* MyList<T>::peek() {
return this->head;
}
template <class T>
T* MyList<T>::get(int index) {
if (index == 0) {
return this->head;
} else if (index == this->list_size - 1) {
return this->tail;
} else if (index < 0 || index >= this->list_size) {
return NULL;
}
if (index < this->list_size / 2) {
T* temp = this->head;
int i = 0;
while (temp) {
if (i == index) { return temp; }
i++;
temp = temp->next;
}
} else {
T* temp = this->tail;
int i = this->list_size - 1;
while (temp) {
if (i == index) { return temp; }
i--;
temp = temp->previous;
}
}
return NULL;
}*/
template <typename T>
void linkedlist<T>::printlist() {
cout << "HEAD: ";
Node<T>* temp = this->head;
while(temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "\b\b\b\b :TAIL" << endl;
}
template <class T>
void linkedlist<T>::printListBackwards() {
cout << "TAIL: ";
Node<T>* temp = this->tail;
while(temp) {
cout << temp->data << " -> ";
temp = temp->previous;
}
cout << "\b\b\b\b :HEAD" << endl;
}
template <typename T>
linkedlist<T>::~linkedlist() {
for(Node<T>* p;!isEmpty();){
p = head->next;
delete head;
head = p;
}
}
EDIT with copy constructor
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include <ctype.h>
using namespace std;
using namespace std;
/*struct AdjListNode
{
int dest;
struct AdjListNode* next;
};
// A structure to represent an adjacency list
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};
// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;
// Create an array of adjacency lists. Size of array will be V
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
// Initialize each adjacency list as empty by making head as NULL
int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
// Adds an edge to an undirected graph
void addEdge(struct Graph* graph, int src, int dest)
{
// Add an edge from src to dest. A new node is added to the adjacency
// list of src. The node is added at the begining
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
// Since graph is undirected, add an edge from dest to src also
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
// A utility function to print the adjacenncy list representation of graph
void printGraph(struct Graph* graph)
{
int v;
for (v = 0; v < graph->V; ++v)
{
struct AdjListNode* pCrawl = graph->array[v].head;
printf("\n Adjacency list of vertex %d\n head ", v);
while (pCrawl)
{
printf("-> %d", pCrawl->dest);
pCrawl = pCrawl->next;
}
printf("\n");
}
}
*/
/* Node Class */
template <typename T>
class Node {
public:
T data;
Node* next;
Node* previous;
Node(T data);
Node();
T getData();
};
template <typename T>
Node<T>::Node() {
this->next = NULL;
this->previous = NULL;
}
template <typename T>
Node<T>::Node(T data) {
this->data = data;
this->next = NULL;
}
template <typename T>
T Node<T>::getData() {
return this->data;
}
/* Linked List: */
template <typename T>
class linkedlist {
private:
Node<T>* head;
Node<T>* tail;
int list_size;
public:
linkedlist();
linkedlist(linkedlist& object);
T getHead();
T getTail();
int size();
void addtail(const T& input);
void addhead(const T& input);
void push(T);
T pop();
//T* peek();
bool isEmpty() const {
return head == NULL;
}
//T* get(int index);
void printlist();
void printListBackwards();
~linkedlist();
};
template <typename T>
linkedlist<T>::linkedlist() {
this->head = NULL;
this->tail = NULL;
this->list_size = 0;
}
template <typename T>
linkedlist<T>::linkedlist(linkedlist &object){
if(object.head == NULL){
head == NULL;
}
else {
head = new Node<T>(object.head->data);
Node<T>* temp = head;
Node<T>* objecthead = object.head;
Node<T>* current = objecthead;
while(current->next != NULL){
temp->next = new Node<T>(current->next->data);
current = current->next;
temp = temp->next;
}
}
}
template <typename T>
T linkedlist<T>::getHead() {
return this->head->data;
}
template <typename T>
T linkedlist<T>::getTail() {
return this->tail->data;
}
template <class T>
int linkedlist<T>::size() {
return this->list_size;
}
template <typename T>
void linkedlist<T>::addtail(const T& input) {
Node<T>* newnode = new Node<T>(input);
newnode->next = NULL;
newnode->previous = NULL;
if (this->head == NULL) {
this->head = newnode;
this->tail = this->head;
this->list_size = this->list_size + 1;
} else {
this->tail->next = newnode;
newnode->previous = this->tail;
this->tail = newnode;
this->list_size = this->list_size + 1;
}
}
template <typename T>
void linkedlist<T>::addhead(const T& input) {
Node<T>* newnode = new Node<T>(input);
newnode->next = NULL;
newnode->previous = NULL;
if (this->head == NULL) {
this->head = newnode;
this->tail = this->head;
this->list_size = this->list_size + 1;
} else {
this->head->previous = newnode;
newnode->next = this->head;
this->head = newnode;
this->list_size = this->list_size + 1;
}
}
template <typename T>
void linkedlist<T>::push(T input) {
this->addhead(input);
}
template <typename T>
T linkedlist<T>::pop() {
Node<T>* temp = this->head;
if(temp != NULL){
this->head = this->head->next;
this->head->previous = NULL;
this->list_size = this->list_size - 1;
return temp->data;
}
else{
cout << "Error:Empty List!";
exit (EXIT_FAILURE);
}
}
/*
template <class T>
T* MyList<T>::peek() {
return this->head;
}
template <class T>
T* MyList<T>::get(int index) {
if (index == 0) {
return this->head;
} else if (index == this->list_size - 1) {
return this->tail;
} else if (index < 0 || index >= this->list_size) {
return NULL;
}
if (index < this->list_size / 2) {
T* temp = this->head;
int i = 0;
while (temp) {
if (i == index) { return temp; }
i++;
temp = temp->next;
}
} else {
T* temp = this->tail;
int i = this->list_size - 1;
while (temp) {
if (i == index) { return temp; }
i--;
temp = temp->previous;
}
}
return NULL;
}*/
template <typename T>
void linkedlist<T>::printlist() {
cout << "STACK" << endl;
cout << "-------------------" << endl;
Node<T>* temp = this->head;
while(temp) {
cout << "\t" << temp->data << endl;
temp = temp->next;
}
//cout << "\b\b\b\b :TAIL" << endl;
}
template <class T>
void linkedlist<T>::printListBackwards() {
cout << "TAIL: ";
Node<T>* temp = this->tail;
while(temp) {
cout << temp->data << " -> ";
temp = temp->previous;
}
cout << "\b\b\b\b :HEAD" << endl;
}
template <typename T>
linkedlist<T>::~linkedlist() {
for(Node<T>* p;!isEmpty();){
p = head->next;
delete head;
head = p;
}
}
#endif // LINKEDLIST_H
I've been building on a template Linked List and recently implemented a user-defined copy constructor to handle deep copies of my Linked List. My current solution compiles just fine but when I execute, nothing is displayed.
#include <iostream>
template<typename T>
class LinkedList
{
private:
struct Node
{
T data;
Node* next;
};
Node* head;
Node* tail;
int size;
public:
LinkedList();
LinkedList(const LinkedList<T> &list);
~LinkedList();
LinkedList<T>& operator=(const LinkedList<T> list);
int getSize() const;
void display() const;
void push(const T &data);
void insert(const int pos, const T &data);
void remove(const int pos);
};
template<typename T>
LinkedList<T>::LinkedList() : head{ nullptr }, tail{ nullptr }, size{ 0 }
{
}
// TODO: User-defined copy constructor
template<typename T>
LinkedList<T>::LinkedList(const LinkedList<T> &list)
: head{ nullptr }, tail{ nullptr }, size{list.size}
{
std::cout << "In the copy constructor\n";
if (list.head == nullptr)
{
return;
}
else
{
Node* curNode = new Node{list.head->data, nullptr};
head = curNode; // sets the head member variable to first node in Linked List
Node* curListNode = list.head;
while (curListNode->next != nullptr)
{
curNode->next = new Node{curListNode->next->data, nullptr};
curListNode = curListNode->next;
curNode = curNode->next;
}
curNode->next = new Node{curListNode->next->data, nullptr};
tail = curNode->next;
}
}
template<typename T>
LinkedList<T>::~LinkedList()
{
Node* prevNode = head;
Node* curNode = head;
while(curNode != nullptr)
{
prevNode = curNode;
curNode = curNode->next;
delete prevNode;
}
head = nullptr;
tail = nullptr;
}
template<typename T>
LinkedList<T>& LinkedList<T>::operator=(const LinkedList<T> list)
{
// make a copy of each node - much like the copy constructor
std::cout << "In the overloaded assignment\n";
}
template<typename T>
int LinkedList<T>::getSize() const
{
return size;
}
template<typename T>
void LinkedList<T>::display() const
{
Node* curNode = head;
while (curNode != nullptr)
{
std::cout << curNode->data << '\n';
curNode = curNode->next;
}
std::cout << '\n';
}
template<typename T>
void LinkedList<T>::push(const T &data)
{
Node* newNode = new Node{data, nullptr};
if (size == 0)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
++size;
}
template<typename T>
void LinkedList<T>::insert(const int pos, const T &data)
{
if (pos < 0 || pos > size)
{
throw "Index is out of range!";
}
else if (pos == size)
{
push(data);
}
else
{
Node* newNode = new Node{data, nullptr};
Node* prevNode = head;
Node* curNode = head;
int i = 0;
while (i != pos)
{
prevNode = curNode;
curNode = curNode->next;
++i;
}
prevNode->next = newNode;
newNode->next = curNode;
++size;
}
}
template<typename T>
void LinkedList<T>::remove(const int pos)
{
if (pos < 0 || pos > size)
{
throw "Index is out of range!";
}
else if (size == 0)
{
throw "List is empty!";
}
else
{
Node* prevNode = head;
Node* curNode = head;
int i = 1;
while (i != pos)
{
prevNode = curNode;
curNode = curNode->next;
++i;
}
prevNode->next = curNode->next;
delete curNode;
if (pos == size)
{
tail = prevNode;
}
--size;
}
}
int main()
{
LinkedList<int> list;
list.push(1);
list.push(3);
list.push(6);
list.display();
LinkedList<int> copyList{list};
copyList.display();
return 0;
}
The first LinkedList<int> list doesn't even display when I add the the copyList statement to main(). However, when I comment out the two copyList statements, list displays as normal.
I added print statements to see if either the copy constructor or the operator= functions were being called and neither of those are printed to the console when the copyList statements are added to my program (the code compiles just fine).
I could use any help to help diagnose what's causing this behavior.
A simple copy constructor like this one should suffice:
template<typename T>
LinkedList<T>::LinkedList(const LinkedList<T> &list)
: head{ nullptr }, tail{ nullptr }, size{0}
{
std::cout << "In the copy constructor\n";
Node* curNode = list.head;
while (curNode != nullptr)
{
this->push(curNode->data);
curNode = curNode->next;
}
}
Note that this is just your display method rewritten to insert elements in the current list.