First making a copy constructor for linked lists was difficult and now this stack. I almost wanted to hit my head with something but then I thought of Stack Overflow guys. So here is the problem:
Consider One thing You can not change the list.h or stack.h or its constructor even.
// In list.h
template <class T>
struct ListItem
{
T value;
ListItem<T> *next;
ListItem<T> *prev;
ListItem(T theVal)
{
this->value = theVal;
this->next = NULL;
this->prev = NULL;
}
};
/* This is the generic List class */
template <class T>
class List
{
ListItem<T> *head;
public:
// Constructor
List();
// Copy Constructor
List(const List<T>& otherList);
}
// In list.cpp
template <class T>
List<T>::List()
{
head=NULL;
}
template <class T>
List<T>::List(const List<T>& otherList)
{
// I have code working for this part
}
template <class T>
List<T>::~List()
{
}
// In stack.h (includes list.cpp)
template <class T>
class Stack
{
List<T> list;
public:
Stack();
Stack(const Stack<T>& otherStack);
~Stack();
void push(T item);
T top();
T pop();
};
// remember top(); pop(); push() functions are working properly in stack.cpp file.
// In stack.cpp (includes stack.h)
Stack(const Stack<T>& otherStack){
}
template <class T>
void Stack<T>::push(T item)
{
}
template <class T>
T Stack<T>::top()
{
}
template <class T>
T Stack<T>::pop()
{
}
there is an object s containing elem from 0 to 100. 100 being on the top.
Now we copy something like this:-
Stack<int> s2(s);
I don’t know how on Earth to access otherStack elements. I mean of course its a linked list. But it is in Stack.cpp, what can I do to access it and also how to make a copy constructor for this stack (Working code would be preferable). And Please be supportive this time. Thanks.
NOTE: You can’t change any constructor. It has to be the way it is. I hope every body this time gets my query.
Assuming that your
List‘s copy constructor works correctly, yourStackshould be fine using the copy constructor generated implicitly by the compiler. That being the case, the complete code for a stack can look something like this:We don’t have to define a copy constructor for Stack, because List’s copy constructor will be used to copy the
datamember (and that’s the only data member ofStack, so copying it is also sufficient to copy theStack).