Select the code snippet which returns the top of the stack.

Như Quỳnh

New member
Select the code snippet which returns the top of the stack.
A.
Code:
public int top()
{
       if(q1.size()>0)
       {
            return q1.poll();
       }
       else if(q2.size()>0)
       {
            return q2.poll();
       }
       return 0;
}
B.
Code:
public int top()
{
       if(q1.size()==0)
       {
            return q1.peek();
       }
       else if(q2.size()==0)
       {
            return q2.peek();
       }
        return 0;
    }
C.
Code:
public int top()
{
       if(q1.size()>0)
       {
            return q1.peek();
       }
       else if(q2.size()>0)
       {
            return q2.peek();
       }
       return 0;
}
D.
Code:
public int top()
{
       if(q1.size()>0)
       {
            return q2.peek();
       }
       else if(q2.size()>0)
       {
            return q1.peek();
       }
       return 0;
}
 
Answer: C
Explanation: Assuming its a push costly implementation, the top of the stack will be in the front end of the queue, note that peek() just returns the front element, while poll() removes the front element from the queue.
 

Tìm kiếm

Back
Top