retagged by
265 views
0 0 votes

Consider the following function:

void f(stack S) {
int x ;
if (!isEmpty(S)) {
        x = pop(S);
        f(S);
        push(S, x);
    }
}

What operation is performed by the above function $f$?

  1. Leaves the stack $S$ unchanged
     
  2. Reverses the order of the elements in the stack $S$
     
  3. Pops the top element of stack $S$
     
  4. Empties the stack $S$

1 Answer

2 2 votes

If Stack $S = [1, 2]$ (top is 2):

  • Call 1: Pop 2, store $x=2$. Call f(S).

  • Call 2: Pop 1, store $x=1$. Call f(S).

  • Call 3: Stack is empty. Return.

  • Back to Call 2: push(S, 1). Stack is now $[1]$.

  • Back to Call 1: push(S, 2). Stack is now $[1, 2]$.

The stack ends in its original state.

Answer:
Position:
Show:

Related questions

0 0 votes
0 0 answers
298
298 views
GO Classes asked Mar 17
298 views
Consider a hash table with $100$ slots. Collisions are resolved using chaining. Assuming simple uniform hashing, what is the probability that the first $3$ slots are unfi...
1 1 vote
1 1 answer
265
265 views
GO Classes asked Mar 17
265 views
Consider the following function that reverses a singly linked list.Node* reverseList(Node* head) { Node* prev = NULL; Node* current = head; Node* next = NULL;...
1 1 vote
1 1 answer
251
251 views
GO Classes asked Mar 17
251 views
Consider inserting the following sequence of keys into an initially empty AVL tree:$$38,53,42,26,33,60,79,21,20$$During the construction of the AVL tree, rotations are pe...
1 1 vote
1 1 answer
265
265 views
GO Classes asked Mar 17
265 views
A queue initially contains the elements (from front to rear):$$1~2~3~4~5~6$$An empty stack is also available. The following operations can be performed:Dequeue an element...