Write the code necessary to convert the following sequence of ListNode objects:
ID: 3869247 • Letter: W
Question
Write the code necessary to convert the following sequence of ListNode objects: list rightarrow [1] rightarrow[2]/Into this sequence of ListNode objects: list rightarrow [1] rightarrow [2]rightarrow [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 List Node (int data) {...} public ListNode (int data, ListNode next) {...} }Explanation / Answer
public class ListNode {
public int data;
public ListNode next;
public ListNode() {
next = null;
data = 0;
}
public ListNode(int data) {
next = null;
this.data = data;
}
public ListNode(int data, ListNode next) {
this.next = next;
this.data = data;
}
public static void main(String args[]) {
// create a listnode with 1 as data
ListNode ln = new ListNode(1);
// add a new listnode with 2 data to l next, and for 2 next add list node 3
ln.next = new ListNode(2, new ListNode(3));
// printing values
System.out.print("list -> [");
while (ln.next != null) {
System.out.print(ln.data + "] -> [");
ln = ln.next;
}
System.out.println(ln.data + "] / ");
}
}
/*
* sample output list -> [1] -> [2] -> [3] /
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.