Choose the code snippet which inserts a node to the head of the list?

Choose the code snippet which inserts a node to the head of the list?
A.
Code:
public void insertHead(int data)
{
	Node temp = new Node(data);
	Node cur = head;
	while(cur.getNext() != head)
		cur = cur.getNext()
	if(head == null)
	{
		head = temp;
		head.setNext(head);
	}
	else
	{
		temp.setNext(head);
		head = temp;
		cur.setNext(temp);
	}
	size++;
}
B.
Code:
public void insertHead(int data)
{
	Node temp = new Node(data);
	while(cur != head)
		cur = cur.getNext()
	if(head == null)
	{
		head = temp;
		head.setNext(head);
	}
	else
	{
		temp.setNext(head.getNext());
		cur.setNext(temp);
	}
	size++;
}
C.
Code:
public void insertHead(int data)
{
	Node temp = new Node(data);
	if(head == null)
	{
		head = temp;
		head.setNext(head);
	}
	else
	{
		temp.setNext(head.getNext());
		head = temp;
	}
	size++;
}
D.
Code:
public void insertHead(int data)
{
	Node temp = new Node(data);
	if(head == null)
	{
		head = temp;
		head.setNext(head.getNext());
	}
	else
	{
		temp.setNext(head.getNext());
		head = temp;
	}
	size++;
}
 
Answer: A
Explanation: If the list is empty make the new node as ‘head’, otherwise traverse the list to the end and make its ‘next’ pointer point to the new node, set the new node’s next point to the current head and make the new node as the head.
 

Tìm kiếm

Back
Top