Examveda

Given below is the Node class to perform basic list operations and a Stack class with a no arg constructor. Select from the options the appropriate push() operation that can be included in the Stack class. Also 'first' is the top-of-the-stack.
class Node
{
	protected Node next;
	protected Object ele;
	Node()
	{
		this(null,null);
	}
	Node(Object e,Node n)
	{
		ele=e;
		next=n;
	}
	public void setNext(Node n)
	{
		next=n;
	}
	public void setEle(Object e)
	{
		ele=e;
	}
	public Node getNext()
	{
		return next;
	}
	public Object getEle()
	{
		return ele;
	}
}
 
class Stack
{
	Node first;
	int size=0;
	Stack()
	{
		first=null;
	}
}

A.

public void push(Object item)
{
	Node temp = new Node(item,first);
	first = temp;
	size++;
}

B.

public void push(Object item)
{
	Node temp = new Node(item,first);
	first = temp.getNext();
	size++;
}

C.

public void push(Object item)
{
	Node temp = new Node();
	first = temp.getNext();
	first.setItem(item);
	size++;
}

D.

public void push(Object item)
{
	Node temp = new Node();
	first = temp.getNext.getNext();
	first.setItem(item);
	size++;
}

Answer: Option A


This Question Belongs to Data Structure >> Introduction To Data Structures

Join The Discussion

Related Questions on Introduction to Data Structures