Swapping stacks

Asked by At

I'm trying to write swap function for 2 same sized stacks. So far I did this, but does not work properly

void swap(stack<int> s1, Stack<int> s2) {
     // check for empty stack
    if (s1.empty() || s2.empty()) {
        return;
    }

    // check for size
    if (s1.size() != s2.size()) {
        return;
    }

    // storing top elements on the stacks
    int temp1 = s1.pop();
    int temp2 = s2.pop();

    // recursive swapping
    swap(s1, s2);

    // inserting elements
    s1.push(temp2);
    s2.push(temp1);

}

0 Answers