That depends on how your stack is implemented. That is, what is the backing store?
If the stack is implemented as an array, then the stack will be initialized with some default capacity, and a current count of 0. Something like:
s = int[10];
count = 0;
When you push something onto the stack, the item is added and the count
is incremented to 1. If you try to push more items than the array will hold, then the array is extended. (Actually, probably a new array is allocated and the existing contents copied to it.)
When you pop something, count
is reduced by 1, and s[count]
is returned. But the array allocation is not changed.
So if the stack is implemented as an array, then copying from one stack to another will require O(n) extra space. At least temporarily.
If the stack is implemented as a linked list:
head > node > node > node ...
Then typically pop
just returns head
, and the new head is the node that head
previously pointed to. In this case, the memory occupied by the stack is reduced with each pop. Of course, adding to the new stack increases the memory allocation by the same amount. So if the stack is implemented as a linked list, then copying from one stack to another is O(1) extra space.