I know there are a lot of similar questions out there - believe me, I've read them - but I can't get this to work. Which is peculiar, because I resolved a similar struggle with a related program just the other day. I realize that the answer to my question quite likely is out there somewhere, but I've spent a good hour or two looking, without much success.
I am trying to build a linked list. The program consists of four files - header files for the linked list and the node, as well as an interace to the list, and the .cpp file containing the main method.
ListTester.cpp
#include "StdAfx.h"
#include "LinkedList.h"
#include <iostream>
#include <string>
using namespace std;
template <typename T>
void main() {
LinkedList<int> a;
a.addFirst(22);
a.addFirst(24);
a.addFirst(28);
LinkedList<int> b;
b = a;
b = b + a;
b += a;
cout<<b;
}
LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "Node.h"
#include "List.h"
#include <ostream>
template <typename T>
class LinkedList : public List {
private:
int n;
Node<T> *first;
Node<T> *last;
public:
LinkedList();
LinkedList(const LinkedList & ll);
~LinkedList();
int size();
void clear();
void addFirst(T data);
void addLast(T data);
T removeFirst();
T removeLast();
T getFirst();
T getLast();
Node<T>* getFirstNode() const;
void addAt(int pos, T data);
T removeAt(int pos);
T getAt(int pos);
LinkedList& operator=(const LinkedList<T> &right);
T operator[](int i);
LinkedList& operator+(const LinkedList<T> &right);
LinkedList& operator+=(const LinkedList<T> &right);
friend std::ostream& operator<<(std::ostream &os, const LinkedList<T> & ll);
};
template <typename T>
LinkedList<T>::LinkedList() {
this->n = 0;
this->first = 0;
this->last = 0;
}
template <typename T>
LinkedList<T>::LinkedList(const LinkedList & ll) {
this-> n = 0;
this-> first = 0;
this-> last = 0;
Node *temp = ll.first;
while(temp) {
addLast(temp->getData());
temp = temp->getNext();
}
}
template <typename T>
void LinkedList<T>::addFirst(T data) {
Node *p = new Node(data, first);
first = p;
if(!n)
last = p;
n++;
}
template <typename T>
void LinkedList<T>::addLast(T data) {
Node *p = new Node(data, 0);
if(!n)
first = last = p;
else {
last->next = p;
last = p;
}
n++;
}
template <typename T>
T LinkedList<T>::removeFirst() {
T a = 0;
if(!n)
throw "Can't retrieve element from empty list!";
a = first->getData();
Node *p = first->next;
delete first;
first = p;
n--;
return a;
}
template <typename T>
T LinkedList<T>::removeLast() {
T a = 0;
if(!n)
throw "Can't retrieve element from empty list!";
if(n == 1) {
a = last->getData();
delete first;
first = last = 0;
}
else {
a = last->getData();
Node *p = first;
while(p->next->next != 0)
p = p->next;
delete p->next;
p->next = 0;
last = p;
}
n--;
return a;
}
template <typename T>
T LinkedList<T>::getFirst() {
if(n < 1)
throw "Can't retrieve element from empty list!";
return first->getData();
}
template <typename T>
T LinkedList<T>::getLast() {
if(n < 1)
throw "Can't retrieve element from empty list!";
return last->getData();
}
template <typename T>
Node<T>* LinkedList<T>::getFirstNode() const {
return first;
}
template <typename T>
int LinkedList<T>::size() {
return n;
}
template <typename T>
T LinkedList<T>::getAt(int pos) {
if(pos >= n)
throw "Element index out of bounds!";
Node *temp = first;
while(pos > 0) {
temp = temp->next;
pos--;
}
return temp->getData();
}
template <typename T>
void LinkedList<T>::clear() {
Node *current = first;
while(current) {
Node *next = current->next;
delete current;
if(next)
current = next;
else
current = 0;
}
}
template <typename T>
void LinkedList<T>::addAt(int pos, T data) {
if(pos >= n)
throw "Element index out of bounds!";
if(pos == 0)
addFirst(data);
else {
Node *temp = first;
while(pos > 1) {
temp = temp->next;
pos--;
}
Node *p = new Node(data, temp->next);
temp-> next = p;
n++;
}
}
template <typename T>
T LinkedList<T>::removeAt(int pos) {
if(pos >= n)
throw "Element index out of bounds!";
if(pos == 0)
return removeFirst();
if(pos == n - 1)
return removeLast();
else {
Node *p = first;
while(pos > 1) {
p = p->next;
pos--;
}
T a = p->next->getData();
Node *temp = p->next;
p->next = p->next->next;
delete temp;
n--;
return a;
}
}
template <typename T>
LinkedList<T>::~LinkedList() {
clear();
}
template <typename T>
LinkedList<T>& LinkedList<T>::operator=(const LinkedList<T> &right) {
if(this != &right) {
n = 0;
first = 0;
last = 0;
Node *temp = right.first;
while(temp) {
addLast(temp->getData());
temp = temp->getNext();
}
}
return *this;
}
template <typename T>
T LinkedList<T>::operator[](int i) {
return getAt(i);
}
template <typename T>
LinkedList<T>& LinkedList<T>::operator+(const LinkedList<T> &right) {
Node *temp = right.first;
while(temp) {
addLast(temp->getData());
temp = temp->getNext();
}
return *this;
}
template <typename T>
LinkedList<T>& LinkedList<T>::operator+=(const LinkedList<T> &right) {
Node *temp = right.first;
while(temp) {
addLast(temp->getData());
temp = temp->getNext();
}
return *this;
}
template <typename T>
std::ostream& operator<<(std::ostream &os, const LinkedList<T> &ll) {
Node *temp = ll.getFirstNode();
while(temp) {
os<<temp->getData()<<std::endl;
temp = temp->getNext();
}
return os;
}
#endif
Node.h
#ifndef NODE_H
#define NODE_H
template <typename T>
class Node {
private:
T data;
public:
Node<T>* next;
T getData();
Node<T>* getNext();
Node(T data, Node<T>* next);
Node(const Node & n);
};
template <typename T>
T Node<T>::getData() {
return data;
}
template <typename T>
Node<T>* Node<T>::getNext() {
return next;
}
template <typename T>
Node<T>::Node(T data, Node<T>* next) {
this->data = data;
this->next = next;
}
template <typename T>
Node<T>::Node(const Node & n) {
data = n.data;
next = n.next;
}
#endif
List.h
#ifndef LIST_H
#define LIST_H
class List
{
public:
virtual void addFirst(int data) = 0;
virtual void addAt(int pos, int data) = 0;
virtual void addLast(int data) = 0;
virtual int getFirst()= 0;
virtual int getAt(int pos) = 0;
virtual int getLast()= 0;
virtual int removeFirst()= 0;
virtual int removeAt(int pos) = 0;
virtual int removeLast()= 0;
virtual int size() = 0;
virtual void clear() = 0;
virtual ~List() {};
};
#endif
For this, I get LNK2019 and LNK1120 linking errors. I know I used to get this when implementing a Queue in separated .h and .cpp files. But worked around it by doing everything in the header. I also know that this can happen when not implementing a named method, but I can't find any of those here. So what's causing this? I wish the compiler / IDE could point me to the possible cause of the error. But then again, if it was an easy task to find the faulty line, I assume it would already do this. VS 2012 btw.
You made main a function template. Not only does this not make sense (there is no mention of the template parameter inside), it's also never instantiated (and even if it was, it probably wouldn't resolve to the correct main that a program needs as a start point).
Furthermore, it should be int main rather than void main.
// template <typename T>
void main() {
LinkedList<int> a;
a.addFirst(22);
a.addFirst(24);
a.addFirst(28);
LinkedList<int> b;
b = a;
b = b + a;
b += a;
cout<<b;
}
You need a main function, not a main function template. That's probably the source of your linker error: no function called "main".
The reason this won't work is primarily because class templates and function templates are never expanded to real code unless they're used. Since main is the entrypoint to your program, you never call main from anywhere and thus no code for main is ever generated.
Furthermore due to the name mangling that C++ compilers do to functions (to handle overloading, templates, namespaces etc) the symbol that will be generated in the resulting assembly for this main template probably won't be the right one. If it's looking for a symbol 'main' and it sees
$__T_float_main_blah_blah_blah
then you won't link anyways. Long story short: main is a function, not a function template.
Related
I'm trying to create a individual List with a templated value, but unfortunately I can not link from my List to the ListElements with templates.
In my main I call List<int> list1; to create a instance of the class List.
A List contains multiple ListElements that contain the value, that should be templated.
Compiler throws an error at
ListElement* first;
ListElement* last;
in List.h.
It says C2955 - 'ListElement' : use of class type requires type argument list
List.h
#pragma once
#include <string>
#include "ListElement.h"
template<class T>
class List
{
private:
ListElement* first;
ListElement* last;
public:
List();
~List();
void printList();
void pushBack(T value);
void pushFront(T value);
};
List.cpp
#include <iostream>
#include "List.h"
template<class T>
List<T>::List()
{
first = NULL;
last = NULL;
}
template<class T>
List<T>::~List()
{
}
template<class T>
void List<T>::pushBack(T value)
{
if (last)
{
ListElement* tmp = last;
last = new ListElement(value);
last->setPrev(tmp);
tmp->setNext(last);
}
else
{
first = new ListElement(value);
last = first;
}
}
template<class T>
void List<T>::pushFront(T value)
{
if (first)
{
ListElement* tmp = first;
first = new ListElement(value);
first->setNext(tmp);
tmp->setPrev(first);
}
else
{
last = new ListElement(value);
first = last;
}
}
template<class T>
void List<T>::printList()
{
if (first)
{
ListElement* tmp = first;
while (tmp)
{
std::cout << tmp->getValue() << std::endl;
if (tmp != last)
tmp = tmp->getNext();
else
break;
}
}
else
{
std::cout << "List is empty!" << std::endl;
}
}
template class List<int>;
template class List<std::string>;
ListElement.h
#pragma once
#include <string>
template<class T>
class ListElement
{
private:
ListElement* next;
ListElement* prev;
T value;
public:
ListElement(T val);
~ListElement();
ListElement* getNext() { return next; }
ListElement* getPrev() { return prev; }
void setNext(ListElement* elem) { next = elem; }
void setPrev(ListElement* elem) { prev = elem; }
T getValue() { return value; }
};
ListElement.cpp
#include "ListElement.h"
template<class T>
ListElement<T>::ListElement(T val)
{
value = val;
}
template<class T>
ListElement<T>::~ListElement()
{
}
template class ListElement<int>;
template class ListElement<std::string>;
ListElement is a template, so you want to use a specific instantiation for your pointers:
template<class T>
class List
{
private:
ListElement<T>* first;
ListElement<T>* last;
// note: ^^^
likewise for other occurrences. Only within the template, the template name is usable for the current instantiation, i.e., within List, you can use List as a shortcut for List<T>.
I'm trying to make a custom set of header files to use a generic List and use operator<< to make it print into a ostream object
There are a couple of errors which I cannot resolve.
I'm trying to make a generic List class using a generic Node class. The generic List should be printed using the operator<< . However I'm getting a lot of errors.
#include <iostream>
using std::cout;
using std::ostream;
class List;
template<class T>
class Node
{
friend class List<Node>;
private:
T data_;
Node *next_;
public:
Node(T data);
T get_data();
};
template<typename T>
Node<T>::Node(T data)
{
data_ = data;
next_ = 0;
}
template<typename T>
T Node<T>::get_data()
{
return data_;
}
template<typename T>
class Node;
template<typename T>
class List
{
template<typename T>
friend ostream& operator<<(ostream& o , const List<T> head);
private:
Node<T> *start_;
bool is_empty();
public:
List();
~List();
void insert(T data);
void remove();
};
template<typename T>
bool List<T>::is_empty()
{
if(start_ == 0)
return true;
return false;
}
template<typename T>
List<T>::List()
{
start_ = 0;
}
template<typename T>
List<T>::~List()
{
if( !is_empty())
{
Node<T> *current = start_;
Node<T> *temp;
while(current != 0)
{
temp = current;
current = current->next_;
delete temp;
}
}
}
template<typename T>
void List<T>::insert(T data)
{
if(is_empty())
{
Node<T> *temp = new Node<T>(data);
start_ = temp;
}
else
{
Node<T> *temp = start_;
while(temp->next_ != 0)
{
temp = temp->next_;
}
temp->next_ = new Node<T>(data);
}
}
template<typename T>
void List<T>::remove()
{
if(start_->next_ == 0)
{
Node<T> *temp = start_->next_;
start_->next_ = 0;
delete temp;
}
else if(!is_empty())
{
Node<T> *stay = start_;
Node<T> *remove = stay->next_;
while(remove->next_ != 0)
{
stay = remove;
remove = remove->next_;
}
stay->next_ = 0;
delete remove;
}
}
// Experimental Stuff out here
template<typename T>
ostream& operator<<(ostream& o , const List<T> *head)
{
Node<T> *temp = head->start_;
if(!is_empty<T>())
{
while(temp->next_ != 0)
{
o << temp.get_data() << "\t";
o << "\n";
temp = temp->next_;
}
}
return o;
}
// End of Experimental Stuff
Assuming clients of your class instantiate it like this:
List<int> my_list;
You need to define your operator << overload like this:
template <typename T>
std::ostream& operator << (std::ostream& os, const List<T>& list)
{
// I'm gonna assume you have C++11
auto node = list.start_;
while (node != nullptr)
{
os << '\t' << node->get_data() << '\n';
node = node->next_;
}
return os;
}
Additionally, there are loads of errors in your code regarding templates, so please fix them first.
This question already has answers here:
Why do I get "unresolved external symbol" errors when using templates? [duplicate]
(3 answers)
Undefined reference to template members
(1 answer)
Closed 10 years ago.
I always get
undefined reference to `Graph::InsertVertex(std::string)'
if I compile my project! Any hints why he cant resolve this reference?
(all Files are in the netbeans project folder)
// main.cpp
#include <cstdlib>
#include <string>
#include "Graph.h"
using namespace std;
int main(int argc, char** argv)
{
Graph<string> *graph = new Graph<string>(); // <--- ERROR
graph->InsertVertex("A");
return 0;
}
// Node.h
#include <iostream>
#include "Graph.h"
template<class T>
class Node
{
friend class Graph;
public:
Node(T val)
{
this->data = val;
this->vertList = NULL;
this->next = NULL;
}
Node(const Node& orig);
virtual ~Node();
private:
T data;
Node<T> *vertList;
Node<T> *next;
int status;
};
// Graph.h
#include <iostream>
#include "Node.h"
template <class T>
class Graph
{
public:
Graph()
{
head = NULL;
}
void InsertVertex(T val);
void InsertEdge(T v_val, T e_val);
void PrintVertices();
void PrintEdges(T v_val);
void DeleteEdge(T v_val, T e_val);
void DeleteVertex(T val);
void bfs();
private:
Node<T> *head;
};
// Graph.cpp
#include "Graph.h"
template <class T>
void Graph<T>::InsertVertex(T val)
{
Node<T> *temp = new Node<T>(val);
if(head == NULL) head = temp;
else
{
Node<T> node = head;
while(node->vertList != NULL)
node = node->vertList;
node->vertList = temp;
}
}
template <class T>
void Graph<T>::InsertEdge(T v_val, T e_val)
{
if (head != NULL)
{
Node<T> *k = head;
Node<T> *t = head;
Node<T> *temp = new Node<T> (e_val);
while (t != NULL)
{
if (t->data == v_val)
{
Node<T> *s = t;
while (s->next != NULL)
s = s->next;
s->next = temp;
while (k != NULL)
{
if(k->data == e_val) break;
k = k->vertList;
}
temp->vertList = k;
return;
}
t = t->vertList;
} // end while loop
}
else std::cout << "Add first vertices to the graph" << std::endl;
}
template <class T>
void Graph<T>::PrintEdges(T v_val)
{
Node<T>* t = head;
while (t != NULL)
{
if (t->data == v_val)
{
while (t->next != NULL)
{
std::cout << t->next->vertList->data << " ";
t = t->next;
}
}
t = t->vertList;
}
}
template <class T>
void Graph<T>::PrintVertices()
{
Node<T>* t = head;
while (t != NULL)
{
std::cout << t->data << " ";
t = t->vertList;
}
}
Typically you want your template methods in the header, so they are compiled when needed. In case you really want to hide it in the implementation file, you have to explicitly instantiate the template in Graph.cpp like
template class Graph<string>;
Since you have to do that for every type T you intend to use with Graph<T>, the point of the template class is somewhat defeated and you better put everything into the header
You need to define member functions in a header file, because when instantiating a template, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument.
In your example:
template <class T>
class Graph {
public:
void InsertVertex(T val) {
Node<T> *temp = new Node<T>(val);
if(head == NULL)
head = temp;
// ...
}
// ...
private:
Node<T> *head;
};
So I am trying to create my own implementation file which contains instructions for a Queue. I decided to use a linked list to implement the Queue class, meaning that I need to use my own Node struct. Unfortunately, I am stuck and don't know how to properly include this within the file.
This is what I have so far:
#include <string>
#ifndef NODE
template <class DataType>
struct Node
{
DataType data;
Node *next;
};
#endif
template <class DataType>
class Queue
{
public:
Queue();
bool isEmpty() const;
void push(const DataType& parameter);
bool peek(DataType& parameter) const;
bool pop(DataType& parameter);
void makeEmpty();
private:
Node<DataType>* front;
Node<DataType>* end;
};
template <class DataType>
Queue<DataType>::Queue()
: front(0), end(0)
{
}
template <class DataType>
bool Queue<DataType>::isEmpty() const {return 0 == front;}
template <class DataType>
void Queue<DataType>::push(const DataType& parameter)
{
Node<DataType>* node = new Node<DataType>;
node->data = parameter;
node->next = 0;
if (end) end->next = node;
else front = node;
end = node;
}
template <class DataType>
bool Queue<DataType>::peek(DataType& parameter) const
{
if (0 == front) return false; // failed
parameter = front->data;
return true; // success
}
template <class DataType>
bool Queue<DataType>::pop(DataType& parameter)
{
if (0 == front) return false; // failed
parameter = front->data;
Node<DataType>* p = front->next;
delete front;
front = p;
if (front == 0) end = 0;
return true; // success
}
template <class DataType>
void Queue<DataType>::makeEmpty()
{
end = 0;
Node<DataType>* p;
while (front)
{
p = front->next;
delete front;
front = p;
}
}
I'm not sure if I am enclosing the struct by the #ifndef correctly (i'm not even sure if this is the route I should be taking :/), should I be doing something similar to this or should I be doing something else with the code for the struct?
You can just drop the #ifdef/#endif entirely
This is a class template and it may occur many times in several tranlation units, as long as all the occurrences are identical (One Definition Rule)
Alternative
Since Node<> is purely a private concern, I'd make it a nested struct.
Here's a little demo making this more 'modern C++' style.
Edit Thanks to #R.MartinhoFernandes for showing a few more improvements and for reviewing this.
#include <memory>
template <typename T>
struct Queue {
Queue() : front(), end(/*nullptr*/) {}
// Copy-And-Swap idiom
// see http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-and-swap
// or http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom
void swap(Queue& q) noexcept {
using std::swap;
swap(q.front, front);
swap(q.end, end);
}
Queue(Queue const& q) : front(), end() {
for(auto it=q.front.get(); it; it=it->next.get())
push(it->data);
}
Queue& operator=(Queue q) {
std::swap(*this, q);
return *this;
}
// end Copy-and-swap
// prevent stack overflows in ~Node if the list grows large (say >1k elements)
~Queue() { clear(); }
bool isEmpty() const {
return !front;
}
void push(T const& data) {
Ptr node(new Node(data));
if (end)
end->next = std::move(node);
else
front = std::move(node);
end = node.get();
}
bool peek(T& data) const {
if(front) data = front->data;
return front.get();
}
bool pop(T& data) {
if(!front) return false;
data = front->data;
front = std::move(front->next);
if(!front) end = nullptr;
return true;
}
void clear() {
end = nullptr;
while(front) front = std::move(front->next);
}
private:
struct Node;
typedef std::unique_ptr<struct Node> Ptr;
struct Node {
Node(T data) : data(std::move(data)), next() {}
T data;
Ptr next;
};
Ptr front;
Node* end;
};
#include <iostream>
int main(int argc, const char *argv[]) {
Queue<int> test;
test.push(1);
test.push(2);
test.push(3);
test.push(5);
test.clear();
test.push(32028);
test.push(10842);
test.push(1839);
test.push(23493);
test.push(9857);
int x;
test.peek(x);
while(test.pop(x)) {
std::cout << x << '\n';
}
}
Note: Perhaps the code in push has been golfed a bit too far, but hey, it shows you how modern C++ requires much less handholding (even without std::make_unique).
Note how I think Clang correctly handles the following version (i.e. with implicit std::move):
void push(const DataType& parameter) {
end = ((end? end->next : front) = Ptr(new Node(parameter))).get();
}
I'm not quite sure why gcc rejects it.
I have been struggling for too long a time now with a rather simple question about how to create a generic linked list in c++. The list should be able contain several types of structs, but each list will only contain one type of struct. The problem arises when I want to implement the getNode() function [see below], because then I have to specify which of the structs it should return. I have tried to substitute the structs with classes, where the getNode function returns a base class that is inherited by all the other classes, but it still does not do the trick, since the compiler does not allow the getNode function to return anything but the base class then.
So here is some code snippet:
typedef struct struct1
{
int param1;
(...)
} struct1;
typedef struct struct2
{
double param1;
(...)
} struct2;
typedef struct node
{
struct1 data;
node* link;
} node;
class LinkedList
{
public:
node *first;
int nbrOfNodes;
LinkedList();
void addNode(struct1);
struct1 getNode();
bool isEmpty();
};
LinkedList::LinkedList()
{
first = NULL;
nbrOfNodes = 0;
}
void LinkedList::addNode(struct1 newData)
{
if (nbrOfNodes == 0)
{
first = new node;
first->data = newData;
}
else
{
node *it = first;
for (int i = 0; i < nbrOfNodes; i++)
{
it = it->link;
}
node *newNode = new node;
newNode->data = newData;
it->link = newNode;
}
nbrOfNodes++;
}
bool LinkedList::isEmpty()
{
return !nbrOfNodes;
}
struct1 LinkedList::getNode()
{
param1 returnData = first->data;
node* deleteNode = first;
nbrOfNodes--;
if (nbrOfNodes)
first = deleteNode->link;
delete deleteNode;
return returnData;
}
So the question, put in one sentence, is as follows: How do I adjust the above linked list class so that it can also be used for struct2, without having to create a new almost identical list class for struct2 objects? As I said above, each instance of LinkedList will only deal with either struct1 or struct2.
Grateful for hints or help
There is already a generic link list available in C++, std::list. It will definitely be more efficient & should suffice for your usage.
If you still want to create your own generic link list
You should consider using templates and create a template implmentation of link list.
In c, where templates are not available the data node is stored in the form of a void* pointer. It takes advantage of the fact that a void pointer can point to any generic data type, You might consider that approach as well.
Basic tempaltes are easy.
Just declare the class as template with a templated type variable.
Now everywhere you have the declare type which you want to be generic, in the class, replace the explicit type name with the templated variable name.
For example, in your code, you want struct1 to be generic, so we replace it with T:
template<class T>
class LinkedList {
public:
node *first;
int nbrOfNodes; LinkedList();
void addNode(T);
T getNode();
bool isEmpty();
};
The STL source would be a piece of code to study.
You could also try https://github.com/simonask/ftl/blob/master/list.hpp
Both use templates, which should be understood to be able to make any generic classes.
Here is a generic implementation without using STL. You can create a templated class with a generic type and instantiate the singly_linked_list.
namespace api
{
template <typename T>
class i_list
{
public:
i_list() = default;
virtual ~i_list(){}
/* Add to front*/
virtual int push_front(T t_value) = 0;
/* Return the front item*/
virtual T top_front() = 0;
/* Remove and return the front elenment */
virtual T pop_front() = 0;
/* Add to the back */
virtual int push_back(T t_value) = 0;
/* Returns the back item */
virtual T top_back() = 0;
/* Removes and returns the back item */
virtual T pop_back() = 0;
/* Is key in the list */
virtual bool find(T t_value) = 0;
/* Remove the key from the list */
virtual int erase(T t_value) = 0;
/* Erases the entire list */
virtual void erase_all() = 0;
/* Is the list empty */
virtual bool empty() = 0;
/* return the size of the list */
virtual size_t size() = 0;
};
}
namespace list
{
template<typename T>
struct node
{
T m_data;
node* m_next;
node* m_jump;
int m_order;
node(T t_data) : m_data(t_data), m_next(nullptr) , m_jump(nullptr), m_order(-1){}
};
template<typename T>
class singly_linked_list : public api::i_list<T>
{
public:
singly_linked_list() : m_head(nullptr), m_size(0){}
~singly_linked_list() {erase_all();}
virtual int push_front(T t_value) override;
virtual T top_front() override;
virtual T pop_front() override;
virtual int push_back(T t_value) override;
virtual T top_back() override;
virtual T pop_back() override;
virtual bool find(T t_value) override;
virtual int erase(T t_value) override;
virtual void erase_all() override;
virtual bool empty() override;
virtual size_t size() override;
template<typename U>
friend node<U>* get_head(singly_linked_list<U>& t_list);
private:
node<T>* get_last_node();
node<T>* get_node_until(size_t t_index);
node<T>* find_node(T t_value);
node<T>* get_node_pointer(size_t t_position);
int find_node_index(T t_value);
singly_linked_list<T> get_all_addresses();
node<T>* m_head = nullptr;
size_t m_size;
};
/* O(1) */
template<typename T>
inline int singly_linked_list<T>::push_front(T t_value)
{
node<T>* new_node = new node<T>(t_value);
new_node->m_next = m_head;
m_head = new_node;
m_size++;
return 0;
}
/* O(1) */
template<typename T>
inline T singly_linked_list<T>::top_front()
{
if (empty())
{
std::cout << " list is empty " << std::endl;
return T();
}
return m_head->m_data;
}
/* O(1) */
template<typename T>
inline T singly_linked_list<T>::pop_front()
{
if (empty())
{
std::cout << " list is empty " << std::endl;
return T();
}
/* Value to be returned */
T value = m_head->m_data;
node<T>* next_node = m_head->m_next;
delete(m_head);
m_head = next_node;
m_size--;
return value;
}
/* O(N) */
template<typename T>
inline int singly_linked_list<T>::push_back(T t_value)
{
node<T>* new_node = new node<T>(t_value);
if (empty())
{
m_head = new_node;
m_size++;
return 0;
}
get_last_node()->m_next = new_node;
m_size++;
return 0;
}
/* O(N) */
template<typename T>
inline T singly_linked_list<T>::top_back()
{
if (empty())
{
std::cout << " list is empty " << std::endl;
return T();
}
return get_last_node()->m_data;
}
/* O(N) */
template<typename T>
inline T singly_linked_list<T>::pop_back()
{
T value;
if (empty())
{
std::cout << " list is empty " << std::endl;
return T();
}
if (size() == 1)
{
value = m_head->m_data;
delete(m_head);
m_head = nullptr;
m_size = 0;
return value;
}
node<T>* last_node = get_last_node();
node<T>* last_node_before = get_node_until(size() -1);
value = last_node->m_data;
delete(last_node);
last_node_before->m_next = nullptr;
m_size--;
return value;
}
/* O(N) - Worst case */
template<typename T>
inline bool singly_linked_list<T>::find(T t_value)
{
return find_node(t_value) != nullptr;
}
/* O(N) - Worst case */
template<typename T>
inline int singly_linked_list<T>::erase(T t_value)
{
/* Node with t_value deos not exists */
if (empty())
return -1;
if (size() == 1)
{
delete(m_head);
m_head = nullptr;
m_size = 0;
return 0;
}
int index = find_node_index(t_value);
if (index == -1)
return index;
node<T>* node_to_erase = get_node_until(index + 1);
node<T>* before_node_to_erase = get_node_until(index);
node<T>* after_node_to_erase = get_node_until(index + 2);
before_node_to_erase->m_next = after_node_to_erase;
delete(node_to_erase);
m_size--;
return 0;
}
/* O(N) - Worst case */
template<typename T>
inline void singly_linked_list<T>::erase_all()
{
while(m_head != nullptr)
{
node<T>* next_node = m_head->m_next;
delete(m_head);
m_size--;
m_head = next_node;
}
}
/* O(1) */
template<typename T>
inline bool singly_linked_list<T>::empty()
{
return (m_head == nullptr);
}
/* O(1) */
template<typename T>
inline size_t singly_linked_list<T>::size()
{
return m_size;
}
template<typename T>
inline node<T>* singly_linked_list<T>::get_last_node()
{
node<T>* start_node = m_head;
node<T>* last_node = nullptr;
/* Traverse until the end */
while (start_node != nullptr)
{
last_node = start_node;
start_node = start_node->m_next;
}
return last_node;
}
template<typename T>
inline node<T>* singly_linked_list<T>::get_node_until(size_t t_index)
{
node<T>* start_node = m_head;
node<T>* until_node = nullptr;
/* Traverse until the a node before last node */
size_t index(1);
while (start_node != nullptr)
{
until_node = start_node;
if (index == t_index)
{
return until_node;
}
start_node = start_node->m_next;
index++;
}
return nullptr;
}
template<typename T>
inline node<T>* singly_linked_list<T>::find_node(T t_value)
{
node<T>* start_node = m_head;
/* Traverse until the end */
while (start_node != nullptr)
{
if (t_value == start_node->m_data)
return start_node;
start_node = start_node->m_next;
}
return nullptr;
}
template<typename T>
inline int singly_linked_list<T>::find_node_index(T t_value)
{
node<T>* start_node = m_head;
/* Traverse until the end */
int index(0);
while (start_node != nullptr)
{
if (t_value == start_node->m_data)
return index;
start_node = start_node->m_next;
index++;
}
/* t_value not found*/
return -1;
}
/* Returns the address of the specified node position
form the linke list chain */
template<typename T>
node<T>* singly_linked_list<T>::get_node_pointer(size_t t_position)
{
auto start_node{m_head};
/* Traverse until the end */
size_t i(0);
while (start_node != nullptr)
{
if(i == t_position)
return start_node;
start_node = start_node->m_next;
i++;
}
return nullptr;
}
template<typename U>
node<U>* get_head(singly_linked_list<U>& t_list)
{
return t_list.m_head;
}
}
struct1 and struct2 have different size in bytes, so sizeof(struct1) != sizeof(struct2). Returning the struct from function requires copying it, so c++ requires you to specify the correct type for it so that correct amount of bytes can be copied. To start correct this problem you need to think in the very low level:
struct GenericStruct {
void *ptr;
size_t size;
type_info t;
};
struct1 extract_struct1(GenericStruct &s);
struct2 extract_struct2(GenericStruct &s)
{
if (s.size != sizeof(struct2)) throw -1;
if (s.t != typeid(struct2)) throw -1;
struct2 *s2 = (struct2*)s.ptr;
return *s2;
}
GenericStruct make_generic(const struct1 &ss)
{
GenericStruct s;
s.ptr = (void*)&ss;
s.size = sizeof(struct1);
s.t = typeid(struct1);
return s;
}
GenericStruct make_generic(const struct2 &ss);
the real problem is that these functions can fail on runtime, if the sizes or types do not match. The copying is obviously also needed:
GenericStruct Copy(const GenericStruct &s);
After these basic primitives exists, you can create a class which has copy constructor and assignment operator which uses these functions to implement proper generic struct support.