Menu
Topics Index
...
`

Linked List Push and Pop


If you need explanation Read this topic

If you need Answer Take test on this topic

Linked List Push and Pop
What will be the output of the following program?
import java.util.*;

public class PushPop
{
    private LinkedList list = new LinkedList();

    public void push(Object v)
    {
        list.addFirst(v);
    }
    public Object pop()
    {
        return list.removeFirst();
    }
    public Object top()
    {
        return list.getFirst();
    }
    public static void main(String[] args)
    {
        PushPop stack = new PushPop();
        for (int i = 40; i >= 30; i--)
            stack.push(new Integer(i));
        System.out.print(stack.top() + " ");
        System.out.print(stack.pop() + " ");
        stack.push(10);
        System.out.print(stack.top() + " ");
        System.out.print(stack.pop() + " ");
        System.out.print(stack.pop());
    }
}

A. 30 30 10 10 31
B. 30 30 31 31 32
C. 30 30 10 31 32
D. Compilation Error because list is declared as private
E. Compilation Error for some other reason
Topic: Stack In Java - java.util.Stack Class

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans is A as per given func order..push stores elements in the form of stack top returns first element pop removes and returns first element

Posted by Teja Potlapally    2014-03-03 09:01:25


ans is A..in for loop elements from 40 to 30 are pushed into the stack;
so the stack top ele is 30...pop removes first ele..so 30 is popped out...similarly 10 is top ele and then is popped out..nw top ele is 31

Posted by Santosh Munugota    2014-03-03 09:11:56


Ans E

Posted by Vinay Jogu    2014-03-03 16:23:13


Congratulations Teja Potlapally. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-03-04 04:23:02


© meritcampus 2019

All Rights Reserved.

Open In App