233k views
2 votes
Write the code necessary to convert the following sequence of ListNode objects: list -> [1] -> [2] / Into this sequence of ListNode objects: list -> [1] -> [2] -> [3] / Assume that you are using ListNode class as defined in the textbook: public class ListNode { public int data; // data stored in this node public ListNode next; // a link to the next node in the list public ListNode() { ... } public ListNode(int data) { ... } public ListNode(int data, ListNode next) { ... } }

User Batt
by
8.2k points

1 Answer

4 votes

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.

User Ronald Hulshof
by
8.7k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.