I have two list, how does one push_back elements from one list to another list?
So I have to create a temporary list. Im limited to placing items at the back of my list (enqueue / push back), I have to use this temporary list as storage to help move items from my main list to this list, add the new item to my main list, and then move back the items from the temporary list back to my main list.
Not sure why he wants us to do it like this when there are much easier ways.
I can only use these btw
(a) void push back(const Object & x); //adds x to the end of list
(b) void pop front(); //removes the object at the front of the list
(c) Object & front(); //returns the object at the front of the list
(d) bool empty() const; //true if empty container
I have written a code but only use 1 list. I cannot figure out how to move elements from the main list to a temporary list and then back to the main after x element has been added. Please any help in modifying my code to work with 2 lists is greatly appreciated.
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
|
#include <iostream>
#include <list>
using namespace std;
template <typename T>
class Stack
{
private:
list<T> Object;
public:
void push(T item);
bool empty();
T top();
void pop();
};
template <typename T> void Stack<T>::push(T x)
{
this->Object.push_back(x);
}
template <typename T> bool Stack<T>::empty()
{
return this->Object.empty();
}
template <typename T> T Stack<T>::top()
{
return this->Object.back();
}
template <typename T> void Stack<T>::pop()
{
this->Object.pop_back();
}
int main()
{
Stack<int> s;
s.push(3);
s.push(2);
s.push(5);
while (!s.empty())
{
int item = s.top();
cout << item;
s.pop();
}
cout << endl;
return 0;
}
|