In: Computer Science
Show the output of the following code. Assume the node is in the usual info-link form with info of the type int. Also, list and ptr are reference variables of the type Node.
list = new Node( );
list.info = 88;
ptr = new Node( );
ptr.info = 41;
ptr.link = null;
list.link = ptr;
ptr = new Node( );
ptr.info = 99;
ptr.link = list;
list = ptr;
ptr = new Node( );
ptr.info = 19;
ptr.link = list.link;
list.link = ptr;
ptr = list;
while(ptr != null)
{
System.out.println(ptr.info);
ptr = ptr.link;
}
Group of answer choices
88, 41, 99, 19
19, 41, 88, 99
41, 99, 88, 19
99, 19, 88, 41
I have implemented the code on an java platform after adding some part in the code( to avoid errors).
The modified code and the o/p is given below:
public class HelloWorld{
public static void main(String []args){
Node list = new Node( );
list.info = 88;
Node ptr = new Node( );
ptr.info = 41;
ptr.link = null;
list.link = ptr;
ptr = new Node( );
ptr.info = 99;
ptr.link = list;
list = ptr;
ptr = new Node( );
ptr.info = 19;
ptr.link = list.link;
list.link = ptr;
ptr = list;
while(ptr != null)
{
System.out.println(ptr.info);
ptr = ptr.link;
}
}
}
class Node
{
int info;
Node link;
Node()
{
info = 0;
link=null;
}
}
O/p
99 19 88 41
Since System.out.println() is used the o/p is in different lines, to get them in the same line we have to write System.out.print(). Answer is optn d.
The execution of code and adding nodes go in the following order:
1) 88
2) 88---> 41
3) 99---> 88 ----> 41
4) 99---> 19 ----> 88----> 41
And hence we get the o/p. If you are satisfied with the answer then please upvote it, If you have any doubts please add in the comments section below.