Write a function called copy Stack to copy the elements of an integer type stack
ID: 3843594 • Letter: W
Question
Write a function called copy Stack to copy the elements of an integer type stack, s1, into another stack, s2, where both s1 and s2 are reference parameters, and s2 is initially empty. copyStack is a global function (non-member) which is only allowed to use the standard stack ADT functions: push, pop, top (or peek), and empty. Furthermore, copyStack cannot create an extra array or any other data structure, but it can use one or two extra variables. When the function ends, s2 contains exactly the same elements as s1, and s1 is exactly as it was initially. Following picture shows an example, before and after copyStack:Explanation / Answer
Here is a code, very similar to c++ or java. I have commented the code to make you understand how am processing.
public static copyStack(Stack s1, Stack s2) {
int size = 0;
int tmpElement;
while (!s1.empty()) { //determine the size of stack
s2.push(s1.pop());
size ++;
}
while(!s2.empty)
s1.push(s2.pop());
for (int i = size; i > 0; i++) { //this loop copies the ith deep element from s1 to s2
for (int j=0; j < i-1; j++) //remove i-1 elements
s2.push(s1.pop());
tmpElement = s1.top(); //copy the ith element(backup)
for (int j=0; j < i-1; j++) //replace back those copied items back to s1
s1.push(s2.pop());
s2.push(tmpElement); //copy the backup element to s2
}
}
I hope you like he code. In case you dont understand the logic and operations of the code, please feel free to comment below. I shall be glad to help you.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.