I am working on a program in which I practice using template classes to write a linked list, with a list container behind the scenes doing most of the operations:
template <typename T>
class LinkedList
{
public:
void add(const T& t) {
q.push_front(t);
}
T pop() {
T t = q.front();
q.pop_front();
return t;
}
T& operator[](int i);
private:
list<T> q;
};
Now I want to implement the [] operator such that I can create a LinkedList object and then do operations such as:
list1[0] = 1;
Currently, I have:
template <typename T>
T& LinkedList<T>::operator[](int i)
{
LinkedList<T> tempList;
int j;
T* getNode;
for(j = 0; j < (i + 1); j++) {
T* currentNode = pop();
tempList.add(currentNode);
if(j == i) {
getNode = currentNode;
}
}
while(tempList.isEmpty == false) {
add(tempList.pop());
}
return *getNode;
}
This is clearly not working and it is because I am somehow messing up getting the reference of the particular element I want and returning it, but I am new to C++ and I do not exactly know what the best way of approaching this problem is.
As far as I can tell, your code is attempting to do a simple thing in an amazingly complicated way. What is wrong with just:
However – I do not understand why you would want this operation. This operation has a time complexity of O(N) (where N is the size of the list). If you want random access to the elements of a list, a resizable array would be a far better data-structure.