Apr 19, 2021 at 11:38am Apr 19, 2021 at 11:38am UTC
Apart from the provision of operator>>, there are several issues with the provided code - notably, no destructor and no copy constructor etc.
Consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#include <iostream>
#include <initializer_list>
template <class type>
class Linkedlist {
private :
template <class type>
class node {
public :
type info {};
node* link {};
node(const type& i) : info(i) {}
};
node<type> *head {}, *tail {};
int counter {};
public :
Linkedlist() {}
Linkedlist(std::initializer_list<type> il) {
for (const auto & i : il)
Append(i);
}
~Linkedlist() {
while (head != nullptr ) {
const auto nd {head->link};
delete head;
head = nd;
}
}
// TO BE PROVIDED IF NEEDED
Linkedlist(const Linkedlist&) = delete ;
Linkedlist& operator =(const Linkedlist&) = delete ;
bool isEmpty() const { return (head == nullptr ); }
type getLast() const {
if (isEmpty()) {
std::cout << "Linked list is empty !!!\n" ;
//assert(!isEmpty());
}
return tail->info;
}
void Append(const type& e) {
auto newnode {new node<type>(e)};
if (isEmpty())
head = tail = newnode;
else {
tail->link = newnode;
tail = newnode;
}
++counter;
}
void print() const {
if (isEmpty())
std::cout << "Linked list is empty !!!\n" ;
else
std::cout << *this ;
}
friend std::ostream& operator <<(std::ostream& os, const Linkedlist< type>& dt) {
for (auto current = dt.head; current != nullptr ; current = current->link)
os << current->info << (current->link != nullptr ? ',' : '\n' );
return os;
}
};
int main()
{
const Linkedlist<int > L {10, 20, 30, 40};
std::cout << L;
}
Last edited on Apr 19, 2021 at 12:14pm Apr 19, 2021 at 12:14pm UTC
Apr 19, 2021 at 11:54am Apr 19, 2021 at 11:54am UTC
... and then there is that hanging comma at the end which so far 3 of us have decided to ignore.
Apr 19, 2021 at 11:57am Apr 19, 2021 at 11:57am UTC
Now fixed in my code above!