Hello, the problem is that i need a copy of *s to save it, so then to cout elements 5 3 1 doing one more while cycle loop written below. Or tell me another way to cout these elements.
It's worth noting that your array still exists on the free-store even after you "pop" the values from the stack (but not after you call delete []). One solution could be to reset top to again point one-past the top of the stack and re-iterate through it -- this time printing the other set of values you need. A reset function would look something like:
#include <iostream>
usingnamespace std;
struct Stack
{
int max_n;
int *s;
int s2;
int top;
Stack(int n) : max_n(n), s(newint[max_n]), top(0) {}
bool isEmpty() const
{
return top <= 0;
}
void push(int x)
{
s[top++] = x;
}
int pop()
{
if(!isEmpty())
return s[--top];
}
void delStack()
{
delete[] s;
}
void reset()
{
top = max_n;
}
};
void PushoPop(int n, Stack s);
int main()
{
int n;
cin >> n;
Stack s(n);
PushoPop(n, s);
return 0;
}
void PushoPop(int n, Stack s)
{
int number;
for (int i = 0; i < n; i++)
{
cin >> number;
s.push(number);
}
while (!s.isEmpty())
{
cout << s.pop();
s.pop();
}
s.reset();
while(!s.isEmpty())
{
s.pop();
cout << s.pop();
}
s.delStack();
}
Additionally, in regards to your mention of copying *s, note that you passed Stack by value which creates a new Stack object, but now you have two Stack objects pointing to the same array in the free-store. If you'd like to copy the dynamically allocated memory on pass-by-value, you'd need to create Stack as a class and create something called a copy constructor that allocates new space on the free-store for array elements.
Note with this solution, I got rid of "topp" since it all can really be handled by "pop"