Doubly linked list insert method - c++

I am currently doing an assignment to learn about doubly linked lists and iterators. I am making an insert() method that takes in an iterator type, as well as the data to add into the list. However, I'm getting an exception on the line I marked in the insert() method, saying:
Exception thrown: read access violation. iter.node was 0xFFFFFFFFFFFFFFEF
I'm not sure if this is a problem with the iterator or the linked list:
#include <cstdlib>
#include <iostream>
using namespace std;
class List {
struct Node {
int data;
Node* next = nullptr;;
Node* prev = nullptr;
};
friend ostream& operator<<(ostream& os, const List& rhs);
public:
class iterator {
friend class List;
Node* node = nullptr;
public:
iterator(Node* node) : node(node) {}
iterator& operator++() {
node = node->next;
return *this;
}
iterator& operator--() {
node = node->prev;
return *this;
}
bool operator==(const iterator& rhs) {
if (node != rhs.node) {
return false;
}
return true;
}
bool operator!=(const iterator& rhs) {
return !(*this == rhs);
}
int operator*() const {
return node->data;
}
iterator& operator->() {
return *this;
}
};
List() {
header = new Node();
trailer = new Node();
header->next = trailer;
header->prev = nullptr;
trailer->prev = header;
trailer->next = nullptr;
}
void push_back(int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->prev = trailer->prev;
newNode->prev->next = newNode;
newNode->next = trailer;
trailer->prev = newNode;
}
void pop_back() {
Node* tempNode = trailer->prev->prev;
tempNode->next = trailer;
trailer->prev = tempNode;
}
void push_front(int data) {
Node* newNode = new Node();
newNode->data = data;
header->next->prev = newNode;
newNode->next = header->next;
newNode->prev = header;
header->next = newNode;
}
void pop_front() {
Node* tempNode = header->next->next;
tempNode->prev = header;
header->next = tempNode;
}
int& front() {
if (header->next == trailer) {
cerr << "List is empty" << endl;
}
return header->next->data;
}
int& back() {
if (trailer->prev == header) {
cerr << "List is empty" << endl;
}
return trailer->prev->data;
}
int front() const {
if (header->next == trailer) {
cerr << "List is empty" << endl;
}
return header->next->data;
}
int back() const {
if (trailer->prev == header) {
cerr << "List is empty" << endl;
}
return trailer->prev->data;
}
int size() const {
int count = 0;
for (iterator i = begin(); i != end(); ++i) {
++count;
}
return count;
}
int& operator[](int index) {
int ind = 0;
for (iterator i = begin(); i != end(); ++i) {
if (ind == index) {
return i.node->data;
}
++ind;
}
}
int operator[](int index) const {
int ind = 0;
for (iterator i = begin(); i != end(); ++i) {
if (ind == index) {
return i.node->data;
}
++ind;
}
}
iterator& begin() {
iterator iter(header->next);
return iter;
}
iterator& end() {
iterator iter(trailer);
return iter;
}
iterator begin() const {
iterator iter(header->next);
return iter;
}
iterator end() const {
iterator iter(trailer);
return iter;
}
iterator& insert(iterator& iter, int data) {
Node* newNode = new Node();
newNode->data = data;
iter.node->prev->next = newNode; //exception is thrown on this line
newNode->prev = iter.node->prev;
newNode->next = iter.node;
iter.node->prev = newNode;
iterator newIter(newNode);
return newIter;
}
void clear() {
Node* iter = header->next;
Node* next;
while (iter != trailer) {
next = iter->next;
delete iter;
iter = nullptr;
iter = next;
}
header->next = trailer;
trailer->prev = header;
}
iterator& erase(iterator& iter) {
for (iterator i = ++begin(); i != end(); ++i) {
if (i == iter) {
Node* tempNode = i.node;
tempNode->prev->next = tempNode->next;
tempNode->next->prev = tempNode->prev;
delete tempNode;
tempNode = nullptr;
return ++i;
}
}
}
public:
private:
Node* header;
Node* trailer;
};
ostream& operator<<(ostream& os, const List& rhs) {
for (int i : rhs) {
os << i << " ";
}
os << endl;
return os;
}
void printListInfo(const List& myList) {
cout << "size: " << myList.size()
<< ", front: " << myList.front()
<< ", back(): " << myList.back()
<< ", list: " << myList << endl;
}
int main() {
List myList;
for (int i = 0; i < 10; ++i) myList.insert(myList.end(), i * i);
printListInfo(myList);
myList.clear();
for (int i = 0; i < 10; ++i) myList.insert(myList.begin(), i * i);
printListInfo(myList);
}

iterator& iterator::begin() and iterator& iterator::end() are returning references to local variables. Since it's these functions that are being passed to List::insert(...) in main via myList.insert(myList.begin(), ..) etc, the insertion function is always going to be operating on an invalid iterator.
Similarly, iterator::insert has a similar issue in which it is returning a local variable by reference:
iterator& insert(...)
{
...
iterator newIter(newNode);
return newIter;
}
Once these functions exit, the local variables are destroyed and so those references that were returned are left dangling - pointing at memory where an object used to be.
A quick fix would be to make sure that those new iterators are not local to that function and are instead initialized on the heap e.g.
iterator& begin() {
iterator* iter = new iterator(header->next);
return *iter;
}
iterator& end() {
iterator* iter = new iterator(trailer);
return *iter;
}
However, this also means that you would have to introduce a way to keep track of those iterators so that you can free the memory once an iterator is no longer needed, perhaps by storing the iterators as a member variable of List instead of storing the begin/end Nodes of List and therefore only accessing the Nodes via the iterators.
I found this due to compiling with warnings on, which is highly recommended!
In member function 'List::iterator& List::begin()':
<source>:151:16: warning: reference to local variable 'iter' returned [-Wreturn-local-addr]
151 | return iter;
| ^~~~
<source>:150:18: note: declared here
150 | iterator iter(header->next);

Related

How to Implement a Iterator class in a LinkedList class

New to c++ and I'm having trouble implementing an Iterator class in my LinkedList. I have a Iterator class defined in the private section of my LinkedList class as follows:
cs_linked_list.h
#ifndef LINKED_LIST_H_
#define LINKED_LIST_H_
#include <initializer_list>
#include <iostream>
namespace cs {
template <typename T>
class LinkedList {
struct Node; // forward declaration for our private Node type
public:
/**Constructs an empty list.**/
LinkedList(){
head_ = nullptr;
}
/**
* #brief Constructs a list from a range.
*
*/
template <class InputIterator>
LinkedList(InputIterator first, InputIterator last) {
for (; first != last; ++first) this->push_back(*first);
}
/** Constructs a list with a copy of each of the elements in `init_list`, in the same order. */
LinkedList(std::initializer_list<T> init_list) {
this->operator=(init_list); // call initializer list assignment
}
/**Constructs a container with a copy of each of the elements in another, in the same order**/
LinkedList(const LinkedList<T>& another){
//TODO
this->operator=(another);
}
/** Destroys each of the contained elements, and deallocates all memory allocated by this list. */
~LinkedList() {
while (this->head_) {
Node* old_head = this->head_;
this->head_ = old_head->next;
delete old_head;
}
}
/**Returns the number of elements in this list.Node *head**/
size_t size() const{ //DONE
//TODO
Node *temp = head_;
size_t len = 0;
while (temp != nullptr){
len++;
temp = temp->next;
}
return len;
}
/**Returns whether the list container is empty (that is, whether its size is 0). **/
bool empty() const{ //DONE
if(size_ == 0){
return true;
} else{
return false;
}
}
/** Appends a copy of `val` to this list. */
void push_back(const T& val) {
Node* new_node = new Node{val};
if (this->size_ == 0) {
this->head_ = this->tail_ = new_node;
} else {
this->tail_->next = new_node;
new_node->prev = this->tail_;
this->tail_ = new_node;
}
++this->size_;
}
/** Prepends a copy of `val` to this list. */
void push_front(const T& val) {
Node* new_node = new Node{val};
if (this->size_ == 0) {
this->head_ = this->tail_ = new_node;
} else {
new_node->next = this->head_;
this->head_->prev = new_node;
this->head_ = new_node;
}
++this->size_;
}
/**Returns a reference to the value in the first element in this list.**/
T& front() const{
return head_->data;
}
/**Returns a reference to the value in the last element in this list. **/
T& back() const{
return tail_->data;
}
/**Deletes the first value in this list. **/
void pop_front(){
Node *temp = head_;
if(empty()){
return;
}
if(temp == tail_){
return;
}
head_ = head_->next;
if (head_ != nullptr) {
head_->prev = nullptr;
} else {
tail_ = nullptr;
}
delete temp;
}
/**Deletes the last value in this list**/
void pop_back(){
if(empty()){
return;
}
if(head_ == tail_){
return;
}
Node *temp = head_;
while(temp->next->next != nullptr){
temp = temp->next;
}
tail_ = temp;
delete tail_->next;
tail_->next = nullptr;
size_--;
}
/**resizes the list so that it contains n elements.**/
void resize(std::size_t n){
//TODO
for (size_t i = 0; i < n; i++){
push_back('\0');
}
}
/**resizes the list so that it contains n elements**/
void resize(std::size_t n, const T &fill_value){
//TODO
for (size_t i = 0; i < n; i++) {
push_back(fill_value);
}
}
/**Removes from the container all the elements that compare equal to val. **/
void remove(const T &val){
//TODO
Node *p1 = head_;
Node *p2 = nullptr;
if(p1 != nullptr && p1->data == val){
head_ = p1->next;
delete p1;
} else {
while (p1 != nullptr && p1->data != val){
p2 = p1;
p1 = p1->next;
}
if (p1 == nullptr) {
return;
}
p2->next = p1->next;
delete p1;
}
}
/**Removes duplicate values from this list**/
void unique(){
//TODO
Node *temp = head_;
while (temp != nullptr && temp->next != nullptr) {
Node *temp2 = temp;
while (temp2->next != nullptr) {
if (temp->data == temp2->next->data) {
Node *temp3 = temp2->next;
temp2->next = temp2->next->next;
delete temp3;
} else {
temp2 = temp2->next;
}
}
temp = temp->next;
}
}
/**Deletes all values in this list.**/
void clear(){
//TODO
while (head_ != nullptr){
Node *temp = head_;
head_ = head_->next;
delete temp;
}
tail_ = nullptr;
size_ = 0;
}
/**Reverses the order of the elements in this list.**/
void reverse(){
//TODO
Node *p1 = head_;
Node *p2 = nullptr;
while (p1 != nullptr) {
Node *temp = p1->next;
p1->next = p2;
p2 = p1;
p1 = temp;
}
head_ = p2;
}
/** Replaces the contents of this list with a copy of each element in `init_list`. */
LinkedList& operator=(std::initializer_list<T> init_list) {
this->size_ = 0;
for (auto&& val : init_list)
this->push_back(val);
return *this;
}
/**Replaces the contents of this list with a copy of each element in another, in the same order.**/
LinkedList& operator=(const LinkedList& another){
//TODO
if (this != &another) {
this->clear();
Node *temp = another.head_;
this->size_ = 0;
while (temp) {
this->push_back(temp->data);
temp = temp->next;
}
}
return *this;
}
/**Compares this list with another for equality.**/
bool operator==(const LinkedList &another){ //DONE
//TODO
auto comp = head_;
auto comp2 = another.head_;
while(comp != nullptr){
if(comp != comp2){
return false;
}
comp = comp->next;
comp2 = comp2->next;
}
return true;
}
/**Compares this list with another for inequality. **/
bool operator!=(const LinkedList &another){ //DONE
//TODO
auto comp = head_;
auto comp2 = another.head_;
while(comp != nullptr){
if(comp != comp2){
return true;
}
comp = comp->next;
comp2 = comp2->next;
}
return false;
}
/** Inserts this list into an ostream, with the format `[element1, element2, element3, ...]` */
friend std::ostream& operator<<(std::ostream& out, const LinkedList& list) {
out << '[';
for (Node* cur = list.head_; cur; cur = cur->next) {
out << cur->data;
if (cur->next)
out << ", ";
}
out << ']';
return out;
}private:
struct Node {
T data;
Node* next = nullptr;
Node* prev = nullptr;
};
Node* head_ = nullptr;
Node* tail_ = nullptr;
std::size_t size_ = 0;
class Iterator {
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = int;
using pointer = T*;
using reference = T&;
// Default constructor
Iterator() {
//TODO
n = nullptr;
}
// Copy constructor
Iterator(const Iterator& other) {
//TODO
this->operator=(other);
}
//Destructor if needed
~Iterator() {
//TODO
while (this->list.head_){
Node *old_head = this->list.head_;
this->list.head_ = old_head->next;
delete old_head;
}
}
// Copy assign
Iterator& operator=(const Iterator& that) {
//TODO
if(this != &that){
this->list.clear();
Node *temp = that.list.head_;
this->list.size_ = 0;
while (temp){
this->list.push_back(temp->data);
temp = temp->next;
}
}
return *this;
}
// Prefix increment
Iterator& operator++() {
//TODO
this->n = this->n->next;
return *this;
}
// Postfix increment
Iterator operator++(int) {
Iterator tmp(*this);
this->operator++();
return tmp;
}
// Prefix decrement
Iterator& operator--() {
//TODO
this->n = this->n->prev;
return *this;
}
// Postfix decrement
Iterator operator--(int) {
Iterator tmp(*this);
this->operator--();
return tmp;
}
// Inequality
bool operator!=(Iterator that) const {
return !(this->operator==(that));
}
// Equality
bool operator==(Iterator that) const {
//TODO
auto temp = list.head_;
auto temp2 = that.list.head_;
while(temp != nullptr){
if(*temp != *temp2){
return false;
}
temp = temp->next;
temp2 = temp2->next;
}
return true;
}
// lvalue dereference
T& operator*() const {
//TODO
return this->n->data;
}
// referring
Iterator* operator->() const {
return this;
}
Iterator begin(){
//TODO
return Iterator(list.head_->next);
}
Iterator end(){
//TODO
return Iterator(list.tail_);
}
private:
Node *n;
LinkedList<T> list;
};
};
} // namespace cs
#endif // LINKED_LIST_H_
Main:
#include "cs_linked_list.h"
#include <iostream>
int main() {
/***TESTING***/
cs::LinkedList<int> list;
// Add few items to the end of LinkedList
list.push_back(1);
list.push_back(2);
list.push_back(3);
std::cout << "Traversing LinkedList through Iterator" << std::endl;
for ( cs::LinkedList<int>::Iterator iter = list.begin();iter != list.end(); iter++) {
std::cout << *iter << " ";
}
std::cout << std::endl;
return 0;
}
Since my Iterator class is private I can't seem to implement my Begin() and End() functions. Should I Make it public or am I missing one crucial step. Instructions say to define a Iterator class in the private section of my LinkedList class.

Memory segmentation fault in the double linked list implementation

Below I have a implementation of Linked List.
While there may be more errors because I have not yet finished, let's focus at the four functions: pop_front, push_front, push_back, pop_back.
Everything seems working, until I try to implement push_back. The testing code throws segmentation fault. I don't have idea why, because like it's pretty symmetric operation to the push_front but just at the another end of the list. And the push_front just works.
#include <iostream>
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include "AbstractList.hxx"
template <class T>
class LinkedList : public AbstractList<T>
{
public:
struct Node
{
T value;
Node *prev;
Node *next;
};
LinkedList()
{
guard = new Node;
guard->prev = nullptr;
guard->next = nullptr;
}
// copy,move construction and assignment are not relevant to the question
~LinkedList()
{
clear();
}
template <class U>
void push_front(U &&x)
{
Node *fresh = new Node;
fresh->value = std::forward<U>(x);
fresh->prev = nullptr;
fresh->next = guard->next;
guard->next = fresh;
if (empty())
{
guard->prev = fresh;
}
}
T pop_front()
{
if (empty())
throw std::out_of_range("List is empty");
Node *toDelete = guard->next;
int temp = toDelete->value;
guard->next = guard->next->next;
delete toDelete;
return temp;
}
template <class U>
void push_back(U &&x)
{
Node *fresh = new Node;
fresh->value = std::forward<U>(x);
fresh->next = nullptr;
guard->prev = fresh;
if (empty())
{
guard->next = fresh;
}
}
/*
T pop_back()
{
if (empty())
throw std::out_of_range("List is empty");
Node *toDelete = guard->prev;
int temp = toDelete->value;
guard->prev = guard->prev->prev;
delete toDelete;
return temp;
}
*/
struct Iterator
{
public:
Node *ptr;
Iterator(Node *ptr_) : ptr(ptr_){};
Iterator &operator++()
{
ptr = ptr->next;
return *this;
}
Iterator &operator++(int)
{
Iterator *temp = this;
ptr = ptr->next;
return *temp;
}
Iterator &operator--()
{
ptr = ptr->prev;
return *this;
}
Iterator &operator--(int)
{
Iterator *temp = this;
ptr = ptr->prev;
return *temp;
}
bool operator==(const Iterator &b)
{
return ptr == b.ptr;
}
bool operator!=(const Iterator &b)
{
return !operator==(b);
}
T &operator*()
{
return ptr->value;
}
};
Iterator find(const T &x)
{
Iterator point = begin();
while (point != end())
{
if (*point == x)
return point;
point++;
}
// or end()?
return nullptr;
}
// usuwa cala liste
void clear()
{
Node *current = guard->next;
while (current != nullptr)
{
Node *next = current->next;
delete current;
current = next;
}
guard->prev = nullptr;
guard->next = nullptr;
}
Iterator erase(Iterator x)
{
Iterator point = begin();
while (point != end())
{
if (point == x)
{
for (point; point != end(); point++)
{
point = ++x;
}
return ++x;
}
point++;
}
return nullptr;
}
template <class U>
Iterator insert(Iterator it, U &&x)
{
for (Iterator point = it; point != end(); point++)
{
(point + 1) = point;
}
it = std::forward<U>(x);
}
int remove(const T &x)
{
int count = 0;
Iterator point = begin();
Iterator last = end();
while (point != last)
{
Iterator next = point;
++next;
if (*point == x)
{
erase(point);
count++;
}
point = next;
}
return count;
}
int size()
{
Iterator point = begin();
int count = 0;
while (point != end())
{
count++;
point++;
}
return count;
}
bool empty()
{
return guard->next == nullptr;
}
Iterator begin() const
{
return Iterator(guard->next);
}
Iterator end() const
{
return Iterator(guard->prev);
}
private:
// head = next, prev = tail
Node *guard;
};
#endif
Testing code:
#include <iostream>
#include "./LinkedList.hxx"
int main(int argc, char *argv[])
{
LinkedList<int> l1;
std::cout << l1.size() << std::endl;
l1.push_front(1);
l1.push_front(2);
l1.push_front(3);
for (auto itr = l1.begin(); itr != l1.end(); itr++)
std::cout << *itr << std::endl;
std::cout << "fpops: " << l1.pop_front() << std::endl;
std::cout << "fpops: " << l1.pop_front() << std::endl;
std::cout << "if empty " << l1.empty() << std::endl;
std::cout << "fpops: " << l1.pop_front() << std::endl;
for (auto itr = l1.begin(); itr != l1.end(); itr++)
std::cout << *itr << std::endl;
std::cout << l1.size() << std::endl;
std::cout << "if empty " << l1.empty() << std::endl;
l1.push_back(1);
std::cout << l1.size() << std::endl;
}

Iterator while loop running extra loop

I have a Doubly linked List class wherein i have a function which uses my classes iterators to loop over the collection. However in 1 specific place it runs for an extra loop and I cannot figure out why.
current merge template
template <typename T>
void DlList<T>::merge(SortedList& other) {
iterator it = back_->prev_;
iterator oit = other.begin();
while (oit.current_->next_ != NULL) {
std::cout << *it << " " << *oit << std::endl;
it.current_->next_ = oit.current_;
back_->prev_ = oit.current_;
//back_->prev_->next_ = back_;
//other.back_->prev_ = other.back_->prev_->prev_;
it++;
oit++;
}
}
It always iterates and extra time and added a null node to the list and I don't understand why.
Any insight is greatly appricicated!
Edit Added full project examples to explain intention of function
I am working on a templated data structure class which is a doubly linked list which uses sentinel nodes.
The list is sorted based on insert() and I am working on a merge function wherein the nodes of each list must be combined into this->list. The nodes must be moved and not have new ones created. and if the same value exists in both lists the other node value must come after the current node value.
I coded what I thought was a logical implementation however the output I get is not as expected and the results do not make sense to me, so if anyone could explain how i am getting the results I have it would be greatly appreciated.
Class Definition
class SortedList {
struct Node {
T data_;
Node* next_;
Node* prev_;
Node(const T& data = T{}, Node* nx = nullptr, Node* pr = nullptr) {
data_ = data;
next_ = nx;
prev_ = pr;
}
};
Node* front_;
Node* back_;
public:
class const_iterator {
friend class SortedList;
Node* current_;
const_iterator(Node* n)
{
current_ = n;
}
public:
const_iterator() {
//Set to safe state
current_ = nullptr;
}
const_iterator& operator++() {
current_ = current_->next_;
return *this;
}
const_iterator operator++(int) {
const_iterator old = *this;
current_ = current_->next_;
return old;
}
const_iterator& operator--() {
current_ = current_->prev_;
return *this;
}
const_iterator operator--(int) {
const_iterator old = *this;
current_ = current_->prev_;
return old;
}
bool operator==(const_iterator rhs) {
return (current_ == rhs.current_) ? true : false;
}
bool operator!=(const_iterator rhs) {
return !(*this == rhs);
}
bool operator>(const_iterator rhs) {
return current_->data_ > rhs->current_->data_;
}
const T& operator*()const {
return current_->data_;
}
};
class iterator :public const_iterator {
friend SortedList;
iterator(Node* n) :const_iterator(n) {};
public:
iterator() : const_iterator() {};
//prefix
iterator& operator++() {
this->current_ = this->current_->next_;
return *this;
}
//post-fix
iterator operator++(int) {
iterator old = *this;
this->current_ = this->current_->next_;
return old;
}
iterator& operator--() {
this->current_ = this->current_->prev_;
return *this;
}
iterator operator--(int) {
iterator old = *this;
this->current_ = this->current_->prev_;
return old;
}
T& operator*() {
return this->current_->data_;
}
const T& operator*()const {
return this->current_->data;
}
};
SortedList(); //done
~SortedList();
SortedList(const SortedList& rhs);
SortedList& operator=(const SortedList& rhs);
SortedList(SortedList&& rhs);
SortedList& operator=(SortedList&& rhs);
iterator begin() {
return iterator(front_->next_);
}
iterator end() {
return iterator(back_);
}
const_iterator cbegin() const {
return const_iterator(front_->next_);
}
const_iterator cend() const {
return const_iterator(back_);
}
iterator insert(const T& data);
iterator search(const T& data);
const_iterator search(const T& data) const;
iterator erase(iterator it);
void merge(SortedList& other);
bool empty() const;
int size() const;
};
first merge function attempt
template <typename T>
void SortedList<T>::merge(SortedList& other) {
iterator it = this->begin();
iterator oit = other.begin();
while (oit != other.end()) {
std::cout << *oit << " " << *it << std::endl;
if (*oit < *it) {
oit.current_->prev_->next_ = oit.current_->next_;
oit.current_->next_->prev_ = oit.current_->prev_;
oit.current_->next_ = it.current_;
oit.current_->prev_ = it.current_->prev_;
it.current_->next_ = oit.current_;
}
else {
oit.current_->prev_->next_ = oit.current_->next_;
oit.current_->next_->prev_ = oit.current_->prev_;
oit.current_->next_ = it.current_->next_;
oit.current_->prev_ = it.current_;
it.current_->prev_ = oit.current_;
}
oit++;
it++;
}
}
main tester
int main() {
int num[] = { 3,5,1,2,6,8,9,11 };
int num2[] = { 1,5,4,6,12,7,8,9 };
SortedList<int> l;
SortedList<int> l2;
for (int i = 0; i < 8; i++)
{
l.insert(num[i]);
l2.insert(num2[i]);
}
SortedList<int>::iterator result;
SortedList<int>::iterator result2 = l2.begin();
result = l.begin();
while (result != l.end()) {
std::cout << *result << " " << *result2 << std::endl;
++result;
++result2;
}
l.merge(l2);
output
1 1
2 4
3 5
5 6
6 7
8 8
9 9
11 12
1 1
2 2
3 3
5 5
6 6
8 8
9 9
11 11
0 0
I dont understand why my second output is showing same the same values for *it and *oit I am pretty certain the error is in how I assign the the oit.current_->next & prev but i am unsure.
any insight is appriciated.
You seem to want to merge two sorted doubly linked lists together. There are several problems with your approach, and so I'll show you my code:
#include <iostream>
using namespace std;
struct node {
node* next;
node* prev;
int val;
node(int i_val)
: next(nullptr),
prev(nullptr),
val(i_val)
{}
};
void connect(node* a, node* b) {
if (a != nullptr) {
if (a->next != nullptr) {
a->next->prev = nullptr;
}
a->next = b;
}
if (b != nullptr) {
if (b->prev != nullptr) {
b->prev->next = nullptr;
}
b->prev = a;
}
}
struct DlList {
node* first_node;
node* last_node;
DlList()
: first_node(nullptr),
last_node(nullptr)
{}
~DlList() {
for (node* n = first_node; n != nullptr; n = n->next) {
delete n->prev;
}
delete last_node;
}
void push(int new_val) {
node* new_node = new node(new_val);
connect(last_node, new_node);
last_node = new_node;
if (first_node == nullptr) {
first_node = new_node;
}
}
void merge_sorted(DlList& other) {
node* this_node = first_node;
node* other_node = other.first_node;
node* n = nullptr; // goes through each node of the new list in order
while (this_node != nullptr || other_node != nullptr) {
node* next_n;
if (other_node == nullptr ||
(this_node != nullptr && this_node->val <= other_node->val)) {
// entered if other_node is nullptr or this_node comes before other_node
next_n = this_node;
this_node = this_node->next;
}
else {
// entered if this_node is nullptr or other_node comes before this_node
next_n = other_node;
other_node = other_node->next;
}
connect(n, next_n);
if (n == nullptr) { // first time through loop
first_node = next_n;
}
n = next_n;
}
last_node = n;
// *this takes ownership of all of other's nodes
other.first_node = nullptr;
other.last_node = nullptr;
}
};
int main() {
std::cout << "running test" << std::endl;
int num[] = { 1,2,3,5,6,8,9,11 };
int num2[] = { 1,4,5,6,7,8,9,12 };
DlList l;
DlList l2;
for (int i = 0; i < 8; i++)
{
l.push(num[i]);
l2.push(num2[i]);
}
l.merge_sorted(l2);
for (node* n = l.first_node; n != nullptr; n = n->next) {
std::cout << n->val << " ";
}
std::cout << std::endl;
}
You may add iterators and other higher-level abstractions later, but for now I think they complicate and obscure the logic. I also did not see a need for a "past-the-end-of-the-list" node in your case, as nullptr would suffice. Though of course these could rather easily be added in if you wanted them to, just for demonstration purposes they are omitted.
Notice how I made a dedicated connect function that does all the pointer assignments as they should be done for two nodes. It handles a bunch of combinations of nullptr cases, too, so you don't need to worry as much about checking for null pointers outside of the function. (Note how the first time through the merge loop, a null n pointer is connected to next_n). Now you hardly need to worry about pointer assignments, and it's clearer when you just say, "connect these two nodes."
My merger function goes through each node in the newly created list. It picks the next node from the two available nodes, from *this and other. It then connects the current node to the next node, and advances the current node to the next node. It has special handling when one or the other of the lists runs out (this_node or other_node becomes nullptr), which indeed happens in the given test case. It takes care to assign first_node and last_node in the correct places, and to clear other after the merge, so as to prevent double ownership issues.

Iterator pointer does not reference the first element

I am trying to implement a LinkedList which can be iterated through in c++.
I have therefore made an Iterator class, such that dereferencing an Iterator would return the first element. However, this has not been working. When I then instantiate a new int LinkedList and attempt to access the first element by dereferencing the result of begin(), I do not retrieve the first element of the list, but a 10 digit number such as '1453755360'
My node class is just composed of two right/left node pointers and a data variable
linkedlist class
template <typename T>
class LinkedList{
public:
LinkedList(){
count =(0);
head =(nullptr);
tail =(nullptr);
}
void push_head(T input){
Node<T> newNode = Node<T>(input);
newNode.left = nullptr;
newNode.right = head;
head = &newNode;
count++;
}
T front(){
T& data = (head->data);
return data;
}
void push_tail(T input){
Node<T> newNode = Node<T>(input);
newNode.right = tail;
newNode.left = nullptr;
tail = &newNode;
count++;
}
T back(){
T& data = (tail->data);
return data;
}
Iterator<T> begin(){
Iterator<T> test = Iterator<T>(head);
return test;
}
private:
int count;
Node<T> *head;
Node<T> *tail;
};
Here is where I am testing the code
LinkedList<int> ll;
ll.push_tail(7);
ll.push_tail(9);
if (*(ll.begin()) == 9) {
cout << "pass" << endl;
} else {
cout << "returned : " << *(ll.begin()) << endl;
}
The push_back() implementation requires that if head is null it has to be set, the same for the push_front with respect to the tail.
You are allocating your node objects on the stack, so they are destroyed automatically when they go out of scope. You are storing pointers to those objects, which leaves the pointers dangling when the objects are destroyed. You need to allocate the nodes on the heap using new instead.
Also, push_front() is not updating tail when the list is empty, and is not updating an existing head to point at the new node when the list is not empty. Similar with push_back().
Try something more like this:
template <typename T>
struct Node
{
T data;
Node *left;
Node *right;
Node(const T &d = T(), Node *l = nullptr, Node *r = nullptr)
: data(d), left(l), right(r) {}
};
template <typename T>
class NodeIterator {
public:
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef std::bidirectional_iterator_tag iterator_category;
NodeIterator(Node<T> *input = nullptr) : cur(input) {}
NodeIterator(const NodeIterator &) = default;
NodeIterator(NodeIterator &&) = default;
~NodeIterator() = default;
NodeIterator& operator=(const NodeIterator &) = default;
NodeIterator& operator=(NodeIterator &&) = default;
reference operator*() {
return cur->data;
}
NodeIterator& operator++ () {
if (cur) cur = cur->right;
return *this;
}
NodeIterator operator++ (int) {
NodeIterator tmp(*this);
if (cur) cur = cur->right;
return tmp;
}
NodeIterator& operator-- () {
if (cur) cur = cur->left;
return *this;
}
NodeIterator operator-- (int) {
NodeIterator tmp(*this);
if (cur) cur = cur->left;
return tmp;
}
bool operator==(const NodeIterator &rhs) const {
return (rhs.cur == cur);
}
bool operator!=(const NodeIterator &rhs) const {
return (rhs.cur != cur);
}
private:
Node<T> *cur;
};
template <typename T>
class LinkedList {
public:
typedef NodeIterator<T> iterator;
LinkedList() : count(0), head(nullptr), tail(nullptr) {}
~LinkedList() {
while (head) {
Node<T> *tmp = head;
head = head->right;
delete tmp;
}
}
void push_front(const T &input) {
Node<T> *newNode = new Node<T>(input, nullptr, head);
if (head) head->left = newNode;
head = newNode;
if (!tail) tail = newNode;
++count;
}
T& front() {
return head->data;
}
void push_back(const T &input) {
Node<T> *newNode = new Node<T>(input, tail, nullptr);
if (!head) head = newNode;
if (tail) tail->right = newNode;
tail = newNode;
++count;
}
T& back() {
return tail->data;
}
iterator begin() {
return iterator(head);
}
iterator end() {
return iterator();
}
private:
int count;
Node<T> *head;
Node<T> *tail;
};
Then you can do this:
LinkedList<int> ll;
ll.push_back(7);
ll.push_back(9);
auto iter = ll.begin();
if (*iter == 7) {
cout << "pass" << endl;
} else {
cout << "returned : " << *iter << endl;
}
You can even do things like this now:
for (LinkedList<int>::iterator iter = ll.begin(), end = ll.end(); iter != end; ++iter) {
cout << *iter << endl;
}
for (int i : ll) {
cout << i << endl;
}

Can't access last element in Doubly Linked List when using end() in for loop

I am implementing a doubly linked List using iterators. The code works fine, except when using iterator::end() I am unable to access the last element in the list. For example the copy constructor cant access the last element(!!whenever I use for(iterator it = lst.begin(); it != lst.end();++it)). The problem looks simple but I cant get my head around it.
#pragma once
#include <iterator>
#include <initializer_list>
#include <iostream>
using namespace std;
template <typename T, class Allocator = std::allocator<T>>
class MyList {
private:
class Link {
public:
Link(const T& d, Link *n = NULL, Link *p = NULL) :next(n), prev(p), data(d) {}
~Link() { }
T data;
Link *next;
Link *prev;
};
Link *head ;
Link *tail ;
size_t s = 0; // ease things up
public:
class iterator:public std::iterator<std::bidirectional_iterator_tag, Link>
{
private:
Link *itr;
public:
iterator() :itr(nullptr) {}
iterator(Link* x) :itr(x) {}
// iterator& operator=(const iterator& i2) {itr = i2.itr;}
iterator(const iterator& i2) : itr(i2.itr) {}
iterator& operator++() {
itr=itr->next;
return *this;
}
iterator& operator--() {
itr = itr->prev;
return *this;
}
bool operator==(const iterator& rhs) {
return itr == rhs.itr;
}
bool operator!=(const iterator& rhs) {
return itr != rhs.itr;
}
T& operator*() {
return itr->data;
}
Link* getLink()const{
return itr;
}
};
MyList() {
head = nullptr;
tail= head;
s=0;
}
MyList(std::initializer_list<T> l)
:MyList(){
for(const auto& i : l){
push_back(i);}
}
//copy consructor
MyList( const MyList<T> &lst)
:MyList(){
for(iterator it = lst.begin(); it != lst.end(); ++it){
push_back(it.getLink()->data);
}
}
MyList& operator=(std::initializer_list<T> &lst) {
//clear any data before adding new one
while(head){
Link *tmp = head;
head = head->next;
delete tmp;
}
head = nullptr;
tail = nullptr;
s = 0;
for(auto i: lst){
push_back(i);
}
}
MyList& operator=(MyList<T> &lst) {
while(head){
Link *tmp = head;
head = head->next;
delete tmp;
}
head = nullptr;
tail = nullptr;
s = 0;
for(iterator it = lst.begin(); it != lst.end();++it) {push_back(it.getLink()->data);}
}
~MyList() {
Link* temp = head;
while (temp != nullptr)
{
temp = temp->next;
delete(head);
head = temp;
}
}
iterator begin() const{
iterator i(this->head);
return i;
}
iterator end() const{
iterator return{tail};
}
void push_back(const T& t) {
Link* newnode = new Link(t);
if (empty()) {
head = newnode;
tail = head;
}
else {
tail->next = newnode;
newnode->prev = tail;
tail = newnode;
}
s++;
}
std::size_t size() const {
return s;
}
bool empty() const {
return !(this->size());
}
};
This is the main.cpp I am testing my code, you can see in () when is the code working and when its failing.
//test default constructor(works!!!)
std::cout << "Testing default constructor"<< std::endl;
MyList<int> a{};
std::cout << "a should be empty: " << (a.empty() ? string("and it is!") : string("but it is not!")) << std::endl;
// push_back two elements(works!!!)
std::cout << "Testing push_back"<< std::endl;
a.push_back(1);
a.push_back(2);
std::cout << "a should be 1,2, and is: " << a << std::endl;
// test initializer list constructor(works!!!!)
std::cout << "Testing initializer list constructor"<< std::endl;
MyList<int> b{1, 2, 3, 4};
std::cout << "b should be 1,2,3,4, and is: " << b << std::endl;
//test copy constructor(doesnt work!! Misses the last element)
std::cout << "Testing copy constructor"<< std::endl;
MyList<int> c(b);
std::cout << "c should be " << b << " and is: " << c << std::endl;
MyList<int> ml{1,2,3,4,5,6};
// (doesnt work!! misss the last element)
for(const int& elem : ml)
std::cout << elem << std::endl;
This is because the standard convention in C++ is that end() points not to the last element, but to the next nonexsitent would-be element after the last.
http://www.cplusplus.com/reference/list/list/end/
In your implementation, iterator end() returns an actual last element which is obviously skipped in the it != lst.end() condition in the for loop:
for(iterator it = lst.begin(); it != lst.end();++it)