Answer:
Following are the question in the Java Programming Language:
public class ListNode // define the class which is already mentioned in the question
{
public int data; //set integer type variable
public ListNode next; //create a next node of the ListNode type
//define constructor for the node with 0 and null
public ListNode()
{
this(0,null); //point to the node with 0 and null
}
//define parameterized constructor with 0 and null
public ListNode(int data)
{
//point to the node with 0 and null
this(data, null);
}
//define parameterized constructor with given data and link
public ListNode(int data, ListNode next) {
//this pointer to point tthe current data
this.data=data;
//this pointer to point next node
this.next=next;
}
//conversion of the string
public String toString()
{
//set string type variable
String str = "list->" + this.data;
//at next node
ListNode listNode = this.next;
//set do-while loop
do
{
//print symbol with data
str += "->" +"["+listNode.data+"]";
//point to the next node
listNode = listNode.next;
} while (listNode != null); // iterating the do while loop
//return the string variable str
return str;
}
public static void main(String[] args)// main function
{
//call and pass value to the constructor
ListNode list3 = new ListNode(3);
//call and pass value to the constructor
ListNode list2 = new ListNode(2, list3);
//call and pass value to the constructor
ListNode list1 = new ListNode(1, list2);
//print list variable.
System.out.println(list1);
}
}
Output:
list->1->2->3
Step-by-step explanation:
Following are the description of the program.
In the following Java Program, we define a class "ListNode" and inside the class.
- Define non-parameterized constructor that points to the node with 0 and null.
- Define parameterized constructor that points to the node with 0 and null.
- Define parameterized constructor that points given data and link .
Finally, we define the main function that passes the value and calls the following constructor.