Part III: Recursion Given the classes Node and SinglyLinkedList in this util.zip package, do the following changes: - Re
Posted: Thu Jul 14, 2022 2:19 pm
Node.java
package util;
public class Node<E> { public E data; public Node<E> next;
@Override public String toString() { return data + ""; } public Node(E data, Node<E> next) { this.data = data; this.next = next; } public Node(E data) { this.data = data; this.next = null; }}
SinglyLinkedList.java
package util;
public class SinglyLinkedList<E> { public Node<E> head; //constructor #1 public SinglyLinkedList() { this.head = null;//creates an empty linkedlist! } //constructor #2 public SinglyLinkedList(Node<E> head) { this.head = head;//creates a linked list with agiven head! } @Override public String toString() { if (head == null)// base case return ""; String result = head + ""; if (head.next != null) result += " -> "; SinglyLinkedList<E> rest = newSinglyLinkedList<E>(head.next);
return result + rest.toString(); }}
Part III: Recursion Given the classes Node and SinglyLinkedList in this util.zip package, do the following changes: - Reimplement the toString method of SinglyLinkedList so that it uses recursion to generate the string representation of the linked list. - Using recursion, implement the size method that gets no parameter and returns the number of elements stored in the linked list.
package util;
public class Node<E> { public E data; public Node<E> next;
@Override public String toString() { return data + ""; } public Node(E data, Node<E> next) { this.data = data; this.next = next; } public Node(E data) { this.data = data; this.next = null; }}
SinglyLinkedList.java
package util;
public class SinglyLinkedList<E> { public Node<E> head; //constructor #1 public SinglyLinkedList() { this.head = null;//creates an empty linkedlist! } //constructor #2 public SinglyLinkedList(Node<E> head) { this.head = head;//creates a linked list with agiven head! } @Override public String toString() { if (head == null)// base case return ""; String result = head + ""; if (head.next != null) result += " -> "; SinglyLinkedList<E> rest = newSinglyLinkedList<E>(head.next);
return result + rest.toString(); }}
Part III: Recursion Given the classes Node and SinglyLinkedList in this util.zip package, do the following changes: - Reimplement the toString method of SinglyLinkedList so that it uses recursion to generate the string representation of the linked list. - Using recursion, implement the size method that gets no parameter and returns the number of elements stored in the linked list.