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

Tiên Hương

New member
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.
Code:
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.
Code:
public void push(Object item)
{
	Node temp = new Node(item,first);
	first = temp;
	size++;
}
B.
Code:
public void push(Object item)
{
	Node temp = new Node(item,first);
	first = temp.getNext();
	size++;
}
C.
Code:
public void push(Object item)
{
	Node temp = new Node();
	first = temp.getNext();
	first.setItem(item);
	size++;
}
D.
Code:
public void push(Object item)
{
	Node temp = new Node();
	first = temp.getNext.getNext();
	first.setItem(item);
	size++;
}
 
Answer: A
Explanation: To push an element into the stack, first create a new node with the next pointer point to the current top-of-the-stack node, then make this node as top-of-the-stack by assigning it to ‘first’.
 

Tìm kiếm

Back
Top