Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need to create a Java function that will print a linked list as a string, such

ID: 3815672 • Letter: I

Question

I need to create a Java function that will print a linked list as a string, such that the linked list 1->2->3->4->Null is returned as "1->2->3->4->Null".

I was given the class Node here:

public class Node {
public int data;
public Node next;
}

As well as a driver here:

public class LinkedListProblemsDriver {

public static void main(String[] args) {
// TODO Auto-generated method stub
   LinkedList<Integer> newlist = new LinkedList<Integer>();
newlist.add(1);
newlist.add(2);
newlist.add(3);
newlist.add(4);
   System.out.println(newlist);
   System.out.println(LinkedListProblems.toString(this.head.data));
}
}

And the unchangeable (no changing parameters, name or public/private/static etc. method to write it in:

public static String toString(Node head) {

}

The problem is, I don't know how to initialize the head node with its next pointer, even with a dummy node. I'm allowed to change the driver, and node class, but cannot change anything with the method except the code I write inside.

Explanation / Answer

HI, Please find my implementation.

Please let me know in case of any issue.

Given:

public class Node {
public int data;
public Node next;
}

public static String toString(Node head) {

String result = ""; // initializing string

if(head == null){
return "Null";
}

while(head != null){

result = result + head.data + "->";

head = head.next;
}

// adding null at last

result = result + "Null";

return result;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote